您的位置:首页 > 编程语言 > Python开发

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 设计模式