.Learning.Python.Design.Patterns.2nd.Edition之单实例模式

本文通过Python代码示例介绍了两种设计模式:单例模式和Borg模式。单例模式确保一个类只有一个实例,并提供全局访问点;而Borg模式则确保所有实例共享相同的状态。文中还对比了两种模式的不同之处。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以慢慢理解。。

对照JAVA

class Singleton(object):
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super(Singleton, cls).__new__(cls)
        return cls.instance

s = Singleton()
print("Object created", s, id(s))

s1 = Singleton()
print("Object created", s1, id(s1))

class SingletonA:
    __instance = None
    def __init__(self):
        if not SingletonA.__instance:
            print("__init__ method called..")
        else:
            print("Instance already created:", self.getInstance())

    @classmethod
    def getInstance(cls):
        if not cls.__instance:
            cls.__instance = SingletonA()
        return cls.__instance

s = SingletonA()
print("Object created", SingletonA.getInstance())
s = SingletonA()

class Borg:
    __shared_state = {"1": "2"}
    def __init__(self):
        self.x = 1
        self.__dict__ = self.__shared_state
        pass

b = Borg()
b1 = Borg()
b.x = 4

print("Borg Object 'b':", b)
print("Borg Object 'b1':", b1)
print("Object State 'b':", b.__dict__)
print("Object State 'b1':", b1.__dict__)

class BorgA:
    _shared_state = {"1": "2"}
    def __new__(cls, *args, **kwargs):
        obj = super(BorgA, cls).__new__(cls, *args, **kwargs)
        obj.__dict__ = cls._shared_state
        return obj

b = BorgA()
b1 = BorgA()
b.x = 4

print("BorgA Object 'b':", b)
print("BorgA Object 'b1':", b1)
print("Object State 'b':", b.__dict__)
print("Object State 'b1':", b1.__dict__)

Paperback: 164 pages Publisher: Packt Publishing - ebooks Account; 2 edition (February 15, 2016) Language: English ISBN-10: 178588803X ISBN-13: 978-1785888038 Key Features Understand the structural, creational, and behavioral Python design patterns Get to know the context and application of design patterns to solve real-world problems in software architecture, design, and application development Get practical exposure through sample implementations in Python v3.5 for the design patterns featured Book Description With the increasing focus on optimized software architecture and design it is important that software architects think about optimizations in object creation, code structure, and interaction between objects at the architecture or design level. This makes sure that the cost of software maintenance is low and code can be easily reused or is adaptable to change. The key to this is reusability and low maintenance in design patterns. Building on the success of the previous edition, Learning Python Design Patterns, Second Edition will help you implement real-world scenarios with Python's latest release, Python v3.5. We start by introducing design patterns from the Python perspective. As you progress through the book, you will learn about Singleton patterns, Factory patterns, and Facade patterns in detail. After this, we'll look at how to control object access with proxy patterns. It also covers observer patterns, command patterns, and compound patterns. By the end of the book, you will have enhanced your professional abilities in software architecture, design, and development. What you will learn Enhance your skills to create better software architecture Understand proven solutions to commonly occurring design issues Explore the design principles that form the basis of software design, such as loose coupling, the Hollywood principle and the Open Close principle among others Delve into the object-oriented programming concepts and find out how they are used in software applications Develop an understanding of Creational Design Patterns and the different object creation methods that help you solve issues in software development Use Structural Design Patterns and find out how objects and classes interact to build larger applications Focus on the interaction between objects with the command and observer patterns Improve the productivity and code base of your application using Python design patterns
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值