python设计模式(原型模式、单例模式)

来源:互联网 发布:安卓生日祝福源码 编辑:程序博客网 时间:2024/06/09 23:48

学习版本3.5.2

1.原型模式

原型模式就是拷贝一个对象实例去生成一个新的对象,当初始化过程复杂的时候这个方法就很方便。

import copyclass CloneMyself(object):    def shallow_copy(self):        return copy.copy(self)    def deep_copy(self):        return copy.deepcopy(self)class ProductA(CloneMyself):    def __init__(self, name, type, color, time):        self.name = name        self.type = type        self.color = color        self.time = time    def print_info(self):        print(self.name,self.type,self.color,self.time)if __name__ == "__main__":    product1 = ProductA("A","1","y","10:00")    product1.print_info()    product2 = product1.shallow_copy()    product2.print_info()    product3 = product1.deep_copy()    product3.print_info()

运行结果

A 1 y 10:00A 1 y 10:00A 1 y 10:00

2.单例模式

单例模式就是一个类有且只有一个对象实例。

class Singleton(object):    _instance = None    def __new__(cls,*args,**kwargs):        if cls._instance is None:            cls._instance = object.__new__(cls,*args,**kwargs)        return cls._instance    def __init__(self):        if not hasattr(self,"num"):            print("create num")            setattr(self,"num",0)    def add(self):        self.num += 1        print("num:",self.num)if __name__ == "__main__":    c1 = Singleton()    c1.add()    c2 = Singleton()    c2.add()

运行结果

create numnum: 1num: 2


原创粉丝点击