.Learning.Python.Design.Patterns.2nd.Edition之单实例模式
可以慢慢理解。。
对照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__)