<人人都懂设计模式>-装饰模式
2024-08-29 20:25:24
书上,真的用一个人穿衣打拌来讲解装饰模式的呢。
from abc import ABCMeta, abstractmethod class Person(metaclass=ABCMeta): def __init__(self, name): self._name = name @abstractmethod def wear(self): print("着装。。。") class Engine(Person): def __init__(self, name, skill): super().__init__(name) self.__skill = skill def get_skill(self): return self.__skill def wear(self): print("我是{}工程师{}。".format(self.get_skill(), self._name)) super().wear() class Teacher(Person): def __init__(self, name, title): super().__init__(name) self.__title = title def get_title(self): return self.__title def wear(self): print("我是{}{}。".format(self._name, self.get_title() )) super().wear() class ClothingDecorator(Person): def __init__(self, person): self._decorated = person def wear(self): self._decorated.wear() self.decorate() @abstractmethod def decorate(self): pass class CasualPantDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一条卡其色休闲裤") class BeltDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一条银色针扣头的黑色腰带") class LeatherShoeDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一双深色休闲皮鞋") class KnittedSweaterDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一件紫红色针织毛衣") class WhiteShirtDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一件白色衬衫") class GlassesDecorator(ClothingDecorator): def __init__(self, person): super().__init__(person) def decorate(self): print("一副方形黑框眼镜") def test_decorator(): tony = Engine("Tony", "客户端") pant = CasualPantDecorator(tony) belt = BeltDecorator(pant) shoes = LeatherShoeDecorator(belt) shirt = WhiteShirtDecorator(shoes) sweater = KnittedSweaterDecorator(shirt) glasses = GlassesDecorator(sweater) glasses.wear() print() decorator_teacher = GlassesDecorator(WhiteShirtDecorator(LeatherShoeDecorator(Teacher("wells", "教授")))) decorator_teacher.wear() test_decorator()
C:\Python36\python.exe C:/Users/Sahara/PycharmProjects/test1/test.py 我是客户端工程师Tony。 着装。。。 一条卡其色休闲裤 一条银色针扣头的黑色腰带 一双深色休闲皮鞋 一件白色衬衫 一件紫红色针织毛衣 一副方形黑框眼镜 我是wells教授。 着装。。。 一双深色休闲皮鞋 一件白色衬衫 一副方形黑框眼镜 Process finished with exit code
最新文章
- linux用户不在sudoers文件中
- Script循环语句 的相关知识跟练习
- 12个JavaScript技巧
- 使用MbrFix.exe修复MBR分区表
- getchar(),gets(),scanf()的差异比较
- easyui toolbar 可以放在datagrid底下
- LeetCode 283
- 【转】关于TP3.2 验证码不显示的问题
- Solr中schema.xml的解释
- iOS设备定位
- unicode编码和中国的相互转换
- Python 邮件发送
- Javascript 的变量提升与预解析
- Python设计模式 - UML - 通信图(Communication Diagram)
- 浅谈左偏树在OI中的应用
- springboot 发送邮件+模板+附件
- Spring Boot 集成 Redis 实现缓存机制
- VGA图像显示组成模块分析
- 调试JS代码的神器
- PHP实现 APP端微信支付功能