原型模式也叫克隆模式,通过拷贝自身的属性来创建一个新的对象,基本方法就是调用copy模块下的 (浅拷贝)copy()
和(深拷贝)deepcopy()
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# prototype.py
# author baiyifengyun
import copy
from datetime import date
"""
原型模式:克隆羊多莉
"""
class Prototype:
def __init__(self):
self._objects = {}
def register_object(self, name, obj):
self._objects[name] = obj
def unregister_object(self, name):
del self._objects[name]
def clone(self, name, **attrs):
obj = copy.deepcopy(self._objects.get(name))
obj.__dict__.update(attrs)
return obj
class Sheep:
def __init__(self):
self.name = '多莉'
self.birthday = date.fromtimestamp(132887776)
def showInfo(self):
return f'我是{self.name},出生于{self.birthday}'
def main():
s = Sheep()
prototype = Prototype()
prototype.register_object('s', s)
s1 = prototype.clone('s')
s1.name = '多莉莉'
s1.birthday = date.fromtimestamp(1439876233)
print('原型体:', s.showInfo())
print('克隆体为', s1.showInfo())
if __name__ == "__main__":
main()
结果为:
![](https://img2020.cnblogs.com/blog/892740/202012/892740-20201229232224136-1313909779.png)