美文网首页
【设计模式】装饰者模式

【设计模式】装饰者模式

作者: lndyzwdxhs | 来源:发表于2017-11-01 10:55 被阅读17次

0x01 意图

动态的给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。

0x02 适用场景

UML类图

实例:穿衣服

0x03 代码

# coding:utf-8

import os
import json
################## component类 ##################
class Person(object):
    def __init__(self, name):
        self.name = name
        
    def show(self):
        print "decorate's", self.name
        
################ decorator抽象类 ################
class Finery(object):
    def __init__(self):
        self.person = None
        
    def decorate(self, person_obj):
        self.person = person_obj
        
    def show(self):
        if self.person != None:
            self.person.show()
            
################ decorator具体类 ################
class Tshirts(Finery):
    def show(self):
        print "------------1"
        super(Tshirts, self).show()
        
class Kz(Finery):
    def show(self):
        print "------------2"
        super(Kz, self).show()
        
class hehe(Finery):
    def show(self):
        print "------------3"
        super(hehe, self).show()
        
################## 客户端代码 ##################
cs = Person('caoshuai')
ts = Tshirts()
kkzz = Kz()
he = hehe()

ts.decorate(cs)
kkzz.decorate(ts)
he.decorate(kkzz)

he.show()

################## 输出的结果 ##################
c:\Users\caoshuai\Desktop>python linshi.py
------------3
------------2
------------1
decorate's caoshuai

欢迎关注微信公众号(coder0x00)或扫描下方二维码关注,我们将持续搜寻程序员必备基础技能包提供给大家。


相关文章

  • 设计模式

    设计模式 单例模式、装饰者模式、

  • 设计模式笔记汇总

    目录 设计原则 “依赖倒置”原则 未完待续... 设计模式 设计模式——策略模式 设计模式——装饰者模式 设计模式...

  • java IO 的知识总结

    装饰者模式 因为java的IO是基于装饰者模式设计的,所以要了解掌握IO 必须要先清楚什么事装饰者模式(装饰者模式...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • JavaScript 设计模式核⼼原理与应⽤实践 之 结构型设计

    JavaScript 设计模式核⼼原理与应⽤实践 之 结构型设计模式 装饰器模式,又名装饰者模式。它的定义是“在不...

  • 8种设计模式:

    主要介绍 单例设计模式,代理设计模式,观察者设计模式,模板模式(Template), 适配器模式,装饰模式(Dec...

  • 装饰者模式

    JavaScript 设计模式 张容铭第十二章 房子装修--装饰者模式 (102页) 装饰者模式(Decorato...

  • Summary of February 2017

    READING Head First 设计模式:完成50%。内容:观察者模式、装饰者模式、工厂模式、单件模式、命令...

  • 装饰对象:装饰者模式

    装饰对象:装饰者模式   这是《Head First设计模式(中文版)》第三章的读书笔记。   装饰者模式,可以称...

  • 设计模式之装饰器模式

    也称装饰者模式、装饰器模式、Wrapper、Decorator。 装饰模式是一种结构型设计模式,允许你通过将对象放...

网友评论

      本文标题:【设计模式】装饰者模式

      本文链接:https://www.haomeiwen.com/subject/bxmwpxtx.html