(Python3 代码实现)《大话设计模式》三:装饰模式

本文通过一个具体实例——模拟人物穿衣过程,介绍了装饰模式的基本概念及其应用。装饰模式可以在不改变现有对象的情况下为其添加新的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

装饰模式

在这里插入图片描述

  • 模式特点:动态地为对象增加额外的职责
  • 程序实例:展示一个人一件一件穿衣服的过程。
  • 代码特点:无
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/1/19 17:41
# @Author  : cch
# @Site    :
# @File    : decorator.py
# @Software: PyCharm

class Person:
    def __init__(self, tname):
        self.name = tname

    def Show(self):
        print("dressed %s" % (self.name))


class Finery(Person):
    componet = None

    def __init__(self):
        pass

    def Decorate(self, ct):
        self.componet = ct

    def Show(self):
        if (self.componet != None):
            self.componet.Show()


class TShirts(Finery):
    def __init__(self):
        pass

    def Show(self):
        print("Big T-shirt ")
        self.componet.Show()


class BigTrouser(Finery):
    def __init__(self):
        pass

    def Show(self):
        print("Big Trouser ")
        self.componet.Show()


if __name__ == "__main__":
    p = Person("somebody")
    bt = BigTrouser()
    ts = TShirts()
    bt.Decorate(p)
    ts.Decorate(bt)
    ts.Show()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值