Python实现设计模式--07.原型模式(Prototype Pattern)
来源:互联网 发布:手机dj软件 编辑:程序博客网 时间:2024/06/03 04:28
原型模式实质上就是复制对象,省去了创建对象、复制属性的过程,另外从性能方面考虑,复制对象也比创建对象高效。
比如我要给三个人发邮件,约周六来我家吃饭。邮件内容都一样,只是收件人不一样,下面用原型模式实现它。
首先,定义邮件结构体:
class Mail: __receiver = '' # 接收方 __subject = '' # 邮件主题 __content = '' # 邮件内容 def __init__(self, receiver): self.__receiver = receiver def get_receiver(self): return self.__receiver def set_receiver(self, receiver): self.__receiver = receiver def get_subject(self): return self.__subject def set_subject(self, subject): self.__subject = subject def get_content(self): return self.__content def set_content(self, content): self.__content = content然后定义邀请人(发送邮件的人):
from copy import copy# 邀请人(发送邮件的人)class Sender: __receivers = () # 要邀请的人 def __init__(self, receivers): self.__receivers = receivers # 发送邮件 def send_mail(self): __mail = Mail('nobody') # 定义原型 __mail.set_subject('周末聚会') __mail.set_content('Hi!Guys。 周六来我家吃大虾') for receiver in self.__receivers: mail = copy(__mail) # 使用python提供的复制对象方法 mail.set_receiver(receiver) print('发送给【' + mail.get_receiver() + '】邮件【' + mail.get_subject() + '】,内容为:【' + mail.get_content() + '】')构造场景:
if __name__ == '__main__': sender = Sender(('刘德华', '张学友', '安吉丽娜')) sender.send_mail()执行结果:
发送给【刘德华】邮件【周末聚会】,内容为:【Hi!Guys。 周六来我家吃大虾】发送给【张学友】邮件【周末聚会】,内容为:【Hi!Guys。 周六来我家吃大虾】发送给【安吉丽娜】邮件【周末聚会】,内容为:【Hi!Guys。 周六来我家吃大虾】
复制对象方法已经是python的一部分了,而且python同时提供了浅复制和深复制方法,我们在实践中就不需要设计这种模式了。
阅读全文
0 0
- Python实现设计模式--07.原型模式(Prototype Pattern)
- 设计模式-原型模式(Prototype Pattern)
- 【设计模式】原型模式(Prototype Pattern)
- 设计模式:创建型模式:原型模式(prototype pattern)
- 设计模式---原型模式(Prototype Pattern)
- 设计模式之原型模式(Prototype Pattern)
- Java设计模式--原型模式【Prototype Pattern】
- 设计模式【原型模式Prototype Pattern】
- 原型模式(Prototype Pattern)
- 原型模式(Prototype Pattern)
- 原型模式(Prototype Pattern)
- 原型模式(Prototype Pattern)
- 原型模式(PROTOTYPE PATTERN )
- 原型模式(prototype pattern)
- 原型模式 (Prototype Pattern)
- 原型模式(Prototype Pattern)
- 原型模式(Prototype Pattern)
- 原型模式(Prototype Pattern)
- 51nod 1280 前缀后缀集合(set)
- CNN(卷积神经网络)、RNN(循环神经网络)、DNN(深度神经网络)的内部网络结构有什么区别?
- Codeforces 842C
- 【半年总结】——化繁为简
- Linux下安装Mysql(yum指令)
- Python实现设计模式--07.原型模式(Prototype Pattern)
- CSS总结——2
- 【HTML5学习笔记】28:CSS3文本效果
- js获取本月开始时间和结束时间
- zoj2318 getout(计算几何)
- HTTP协议下GET与POST的区别
- Leetcode 287. Find the Duplicate Number
- 分布式数据库架构及企业实践--基于Mycat中间件pdf
- MySQL袖珍参考手册(第2版)pdf