Python设计模式之原型模式实例详解

不是因为生活太现实,而对生活失望;而是知道生活太现实,所以更要用心的活下去。给自己一个拥抱。

本文实例讲述了Python设计模式之原型模式。分享给大家供大家参考,具体如下:

原型模式(Prototype Pattern):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象

一个原型模式的简单demo:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Andy'
"""
大话设计模式
设计模式——原型模式
原型模式(Prototype Pattern):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象
原型模式是用场景:需要大量的基于某个基础原型进行微量修改而得到新原型时使用
"""
from copy import copy, deepcopy
# 原型抽象类
class Prototype(object):
  def clone(self):
    pass
  def deep_clone(self):
    pass
# 工作经历类
class WorkExperience(object):
  def __init__(self):
    self.timearea = ''
    self.company = ''
  def set_workexperience(self,timearea, company):
    self.timearea = timearea
    self.company = company
# 简历类  
class Resume(Prototype):
  def __init__(self,name):
    self.name = name
    self.workexperience = WorkExperience()
  def set_personinfo(self,sex,age):
    self.sex = sex
    self.age = age
    pass
  def set_workexperience(self,timearea, company):
    self.workexperience.set_workexperience(timearea, company)
  def display(self):
    print self.name
    print self.sex, self.age
    print '工作经历',self.workexperience.timearea, self.workexperience.company
  def clone(self):
    return copy(self)
  def deep_clone(self):
    return deepcopy(self)
if __name__ == '__main__':
  obj1 = Resume('andy')
  obj2 = obj1.clone() # 浅拷贝对象
  obj3 = obj1.deep_clone() # 深拷贝对象
  obj1.set_personinfo('男',28)
  obj1.set_workexperience('2010-2015','AA')
  obj2.set_personinfo('男',27)
  obj2.set_workexperience('2011-2017','AA') # 修改浅拷贝的对象工作经历
  obj3.set_personinfo('男',29)
  obj3.set_workexperience('2016-2017','AA') # 修改深拷贝的对象的工作经历
  obj1.display()
  obj2.display()
  obj3.display()

运行结果:

andy
男 28
工作经历 2011-2017 AA
andy
男 27
工作经历 2011-2017 AA
andy
男 29
工作经历 2016-2017 AA

上面类的设计如下图:

简历类Resume继承抽象原型的clone和deepclone方法,实现对简历类的复制,并且简历类引用工作经历类,可以在复制简历类的同时修改局部属性

希望本文所述对大家Python程序设计有所帮助。

本文Python设计模式之原型模式实例详解到此结束。当你尽了自我的最大努力时,失败也是伟大的。小编再次感谢大家对我们的支持!

您可能有感兴趣的文章
Python自动化运维-使用Python脚本监控华为AR路由器关键路由变化

Python自动化运维-netmiko模块设备自动发现

Python自动化运维—netmiko模块连接并配置华为交换机

Python自动化运维-利用Python-netmiko模块备份设备配置

Python自动化运维-Paramiko模块和堡垒机实战