[Python设计模式] 第9章 如何准备多份简历——原型模式
github地址:https://github.com/cheesezh/python_design_patterns
题目
设计一个简历类,必须有姓名,可以设置性别和年龄,即个人信息,可以设置曾就职公司和工作时间,即工作经历。
基础版本
class Resume():
def __init__(self, name):
self.name = name # python默认成员变量公开
self.__sex = None # python默认成员变量公开,加__表示私有
self.__age = None # python默认成员变量公开,加__表示私有
self.__time_area = None # python默认成员变量公开,加__表示私有
self.__company = None # python默认成员变量公开,加__表示私有
def set_personal_info(self, sex, age):
self.__sex = sex
self.__age = age
def set_work_experience(self, time_area, company):
self.__time_area = time_area
self.__company = company
def display(self):
print("{}\t{}\t{}".format(self.name, self.__sex, self.__age))
print("{}\t{}".format(self.__time_area, self.__company))
def main():
resume_a = Resume("鸣人")
resume_a.set_personal_info("男", "29")
resume_a.set_work_experience("2016-2018", "木叶公司")
resume_b = Resume("鸣人")
resume_b.set_personal_info("男", "29")
resume_b.set_work_experience("2016-2018", "木叶公司")
resume_c = Resume("鸣人")
resume_c.set_personal_info("男", "29")
resume_c.set_work_experience("2016-2018", "木叶公司")
resume_a.display()
resume_b.display()
resume_c.display()
main()
鸣人 男 29
2016-2018 木叶公司
鸣人 男 29
2016-2018 木叶公司
鸣人 男 29
2016-2018 木叶公司
点评
- 上述main函数中生成简历的方法,相当于手写简历,三份简历要三次实例化
- 而且如果要更改某个字段,比如把时间从
2016-2018改成2017-2018,那么同样修改三次
那如果这样写呢?
def main():
resume_a = Resume("鸣人")
resume_a.set_personal_info("男", "29")
resume_a.set_work_experience("2016-2018", "木叶公司")
resume_b = resume_a
resume_c = resume_a
resume_a.display()
resume_b.display()
resume_c.display()
main()
鸣人 男 29
2016-2018 木叶公司
鸣人 男 29
2016-2018 木叶公司
鸣人 男 29
2016-2018 木叶公司
点评
- 这里传递的是引用,而不是具体的值,相当于在简历b和简历c上没有实际内容,而是写着“详见简历a”
- 可以使用clone的方法解决这个问题,即原型模式
原型模式
原型模式,即用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象[DP]。也就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。
from abc import ABCMeta, abstractmethod
from copy import copy
class Prototype():
"""
抽象原型类
"""
__metaclass__ = ABCMeta
def __init__(self, id):
self.id = id
@abstractmethod
def clone(self):
pass
class ConcretePrototypeOne(Prototype):
"""
具体原型类
"""
def __init__(self, id):
super().__init__(id)
def clone(self):
return copy(self) # 1. 浅拷贝copy.copy() 或 深拷贝copy.deepcopy() 2. Python无需强制类型转换
def main():
prototype1 = ConcretePrototypeOne("1")
prototype1_cloned = prototype1.clone()
print(prototype1_cloned.id)
main()
1
Python中的浅拷贝与深拷贝
Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块。
- copy.copy(浅拷贝):只拷贝顶层对象,不会拷贝顶层对象的内部的对象成员变量;
- copy.deepcopy(深拷贝):拷贝对象及其子对象
按照基础版本的简历类定义,成员变量的类型都是基本数据类型(string),所以使用浅拷贝即可。那么什么时候用深拷贝呢?假如我们将工作经历定义为一个单独的类WorkExperience,那么简历类中就会有一个成员变量的类型是WorkExperience,如果这时候需要拷贝操作,就需要用深拷贝了。
深拷贝原型模式
from copy import deepcopy
class WorkExperience():
def __init__(self, time_area="", company=""):
self.time_area = time_area
self.company = company
class Resume():
def __init__(self, name):
self.name = name # python默认成员变量公开
self.__sex = None # python默认成员变量公开,加__表示私有
self.__age = None # python默认成员变量公开,加__表示私有
self.__work_expereince = WorkExperience() # python默认成员变量公开,加__表示私有
def set_personal_info(self, sex, age):
self.__sex = sex
self.__age = age
def set_work_experience(self, time_area, company):
self.__work_expereince.time_area = time_area
self.__work_expereince.company = company
def display(self):
print("{}\t{}\t{}".format(self.name, self.__sex, self.__age))
print("{}\t{}".format(self.__work_expereince.time_area, self.__work_expereince.company))
def deep_clone(self):
"""
深拷贝方法
"""
return deepcopy(self)
def clone(self):
"""
浅拷贝方法
"""
return copy(self)
def main():
resume_a = Resume("鸣人")
resume_a.set_personal_info("男", "29")
resume_a.set_work_experience("2016-2018", "木叶公司")
resume_b = resume_a.clone()
resume_b.set_work_experience("2018-2019", "王者学校")
resume_c = resume_a.clone()
resume_c.set_personal_info("男", "24")
resume_c.set_work_experience("2019-2020", "问问公司")
resume_a.display()
resume_b.display()
resume_c.display()
def deep_main():
resume_a = Resume("鸣人")
resume_a.set_personal_info("男", "29")
resume_a.set_work_experience("2016-2018", "木叶公司")
resume_b = resume_a.deep_clone()
resume_b.set_work_experience("2018-2019", "王者学校")
resume_c = resume_a.deep_clone()
resume_c.set_personal_info("男", "24")
resume_c.set_work_experience("2019-2020", "问问公司")
resume_a.display()
resume_b.display()
resume_c.display()
print("---浅拷贝, 工作经历都被修改成最后一次的值---")
main()
print("--------深拷贝, 工作经历为不同的值--------")
deep_main()
---浅拷贝, 工作经历都被修改成最后一次的值---
鸣人 男 29
2019-2020 问问公司
鸣人 男 29
2019-2020 问问公司
鸣人 男 24
2019-2020 问问公司
--------深拷贝, 工作经历为不同的值--------
鸣人 男 29
2016-2018 木叶公司
鸣人 男 29
2018-2019 王者学校
鸣人 男 24
2019-2020 问问公司
[Python设计模式] 第9章 如何准备多份简历——原型模式的更多相关文章
- [Python设计模式] 第7章 找人帮忙追美眉——代理模式
github地址:https://github.com/cheesezh/python_design_patterns 题目1 Boy追求Girl,给Girl送鲜花,送巧克力,送洋娃娃. class ...
- [Python设计模式] 第15章 如何兼容各种DB——抽象工厂模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 如何让一个程序,可以灵活替换数据库? 基础版本 class User(): ...
- 2.6 《硬啃设计模式》第8章 复制不是很难 - 原型模式(Prototype Pattern)
案例: 某即时战略游戏,你训练出来各种很强的战士. 为了增加游戏的可玩性,增加了一种复制魔法.实施该魔法,可以复制任意的战士. 你会怎样考虑这个设计? 在继续阅读之前,请先认真思考并写出你的设计,这样 ...
- [Python设计模式] 第21章 计划生育——单例模式
github地址:https://github.com/cheesezh/python_design_patterns 单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式 ...
- [Python设计模式] 第1章 计算器——简单工厂模式
github地址:https://github.com/cheesezh/python_design_patterns 写在前面的话 """ 读书的时候上过<设计模 ...
- [Python设计模式] 第22章 手机型号&软件版本——桥接模式
github地址:https://github.com/cheesezh/python_design_patterns 紧耦合程序演化 题目1 编程模拟以下情景,有一个N品牌手机,在上边玩一个小游戏. ...
- [Python设计模式] 第28章 男人和女人——访问者模式
github地址:https://github.com/cheesezh/python_design_patterns 题目 用程序模拟以下不同情况: 男人成功时,背后多半有一个伟大的女人: 女人成功 ...
- [Python设计模式] 第26章 千人千面,内在共享——享元模式
github地址:https://github.com/cheesezh/python_design_patterns 背景 有6个客户想做产品展示网站,其中3个想做成天猫商城那样的"电商风 ...
- [Python设计模式] 第27章 正则表达式——解释器模式
github地址:https://github.com/cheesezh/python_design_patterns 解释器模式 解释器模式,给定一个语言,定一个它的文法的一种表示,并定一个一个解释 ...
随机推荐
- DFMZ-开发过程中遇到的错误-01
未能加载文件或程序集“H2F, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”或它的某一个依赖项.试图加载格式不正确的程序. 原因分析:由 ...
- AOJ 0189 Convenient Location (Floyd)
题意: 求某一个办公室 到其他所有办公室的 总距离最短 办公室数 不超过10 输入:多组输入,每组第一行为n (1 ≤ n ≤ 45),接下来n行是 (x, y, d),x到y的距离是d输出:办公室 ...
- Go 语言 IDE 之 VSCode 配置使用
Gogland 是 JetBrains 公司推出的 Go 语言集成开发环境.Gogland 同样基于 IntelliJ 平台开发,支持 JetBrains 的插件体系.官方:https://www.j ...
- 用jQuery监听浏览器窗口的变化
$(window).resize(function () { //当浏览器大小变化时 alert($(window).height()); //浏览器时下窗口可视区域高度 alert($(docume ...
- Ajax提交form表单内容和文件(jQuery.form.js)
jQuery官网是这样介绍form.js A simple way to AJAX-ify any form on your page; with file upload and progress s ...
- 微信小程序介绍
1.什么是微信小程序 是一种不需要下载即可使用的应用,实现了“触手可及的梦想”,用户扫一扫或者搜一下即可打开. 免安装 操作更接近原始的APP 必须在微信中使用 2.宣传方式 小程序搜索入口 附近的小 ...
- Python爬虫之正则表达式的使用(三)
正则表达式的使用 re.match(pattern,string,flags=0) re.match尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none 参数 ...
- HQL count(*)
public int getTarPage() { String hql = "'"; Query query = getSession().creat ...
- 在Spring中配置SQL server 2000
前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ...
- 【Java并发核心七】计划任务ScheduleExecutorService
Java中定时任务Timer工具类提供了计划任务的实现,但是Timer工具类是以队列的方式来管理线程的,并不是以线程池的方式,这样在高并发的情况下,运行效率会有点低. ScheduleExecutor ...