首页 > 编程 > Python > 正文

Python设计模式之装饰模式实例详解

2019-11-25 13:25:53
字体:
来源:转载
供稿:网友

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

装饰模式(Decorator Pattern):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活.

下面是一个给人穿衣服的过程,使用装饰模式:

#!/usr/bin/env python# -*- coding:utf-8 -*-__author__ = 'Andy'"""大话设计模式设计模式――装饰模式装饰模式(Decorator Pattern):动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活.特点: 有效的把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑"""# 定义对象接口class Person(object):  def __init__(self,name):    self.name = name  def show(self):    print "装扮的%s"%self.name#装饰类class Finery(Person):  def __init__(self):    pass  def Decorate(self,componet):    self.componet = componet  def show(self):    if self.componet != None:      self.componet.show()#装扮――T恤class TShirts(Finery):  def __init__(self):    pass  def show(self):    print 'T恤'    self.componet.show()#装扮――大裤衩class BigTrouser(Finery):  def __init__(self):    pass  def show(self):    print '大裤衩'    self.componet.show()# 装扮――人字拖class FlipFlops(Finery):  def __init__(self):    pass  def show(self):    print '人字拖'    self.componet.show()if __name__ == '__main__':  p = Person('Andy')  ff = FlipFlops()  bt = BigTrouser()  ts = TShirts()  ff.Decorate(p)  bt.Decorate(ff)  ts.Decorate(bt)  ts.show()

运行结果:

T恤
大裤衩
人字拖
装扮的Andy

这几个类的设计如下图:

通过一个个继承自装饰类Finery的对象,实现给Person类赋予职责的功能,Person类并不会感知Finery的存在

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表