python是在Prototype模式和Singleton模式

#-*-coding:utf-8-*-


'''
意图:用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象
'''
from abc import ABCMeta
import copy

class Prototype:
    def shallowClone(self):
        return copy.copy(self)
    def deepClone(self):
        return copy.deepcopy(self)   


if __name__ == "__main__":
     pass


#-*-coding:utf-8-*-


'''
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点
'''

class Singleton(type):
    def __init__(cls, name, bases, dict): #使得不能实例化
        super(Singleton, cls).__init__(name, bases, dict)
        cls.instance = None

    def __call__(cls, *args, **kw): #引用类时返回实例
        if cls.instance is None:
            cls.instance = super(Singleton, cls).__call__(*args, **kw)
        return cls.instance

class MyClass(object):
    __metaclass__ = Singleton
    def printA4(self):
        print 'this A4'
    
if __name__ == "__main__":
    c1 = MyClass()
    c2 = MyClass()
#    if c1 is c2:
    if id(c1) is id(c2):
        print 'Same'
    else:
        print 'Different'
    c1.printA4()


你可能感兴趣的:(Python)