python设计模式(原型模式、单例模式)
2017-10-31 16:24
387 查看
学习版本3.5.2
1.原型模式原型模式就是拷贝一个对象实例去生成一个新的对象,当初始化过程复杂的时候这个方法就很方便。
import copy class 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:00 A 1 y 10:00 A 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 num num: 1 num: 2
相关文章推荐
- python 设计模式学习 —— 原型模式
- Python的创建型设计模式之原型模式与单例模式
- 设计模式-原型模式-prototype-python
- Python设计模式(6)-原型模式
- Python设计模式(十一)【原型模式】
- 设计模式中的原型模式在Python程序中的应用示例
- 设计模式之python版(六)--原型模式
- 用Python讲解原型设计模式
- 设计模式八(原型模式,python语言实现)
- python设计模式之原型模式
- python创建型设计模式——原型模式、单例模式
- Python设计模式——原型模式
- python设计模式-原型设计
- [Python模块学习]copy模块,设计模式中的原型模式
- Python实现设计模式--07.原型模式(Prototype Pattern)
- 设计模式(四) 原型模式(Prototype)
- Java设计模式——原型模式
- 4.原型模式(设计模式笔记)
- 设计模式之创造型模式(抽象工厂模式、建造者模式、工厂模式、原型模式、单例模式)
- Python设计模式(1):设计模式的定义和分类