装饰模式(Decorator)动态的给一个对象添加一些额外的职责,就增加的功能来说,装饰模式比生成子类更灵活(继承的方式,子类和父类存在耦合关系)。
一.Demo需求的提出:
假设现在有一个电脑城的装机报价单打印程序。程序需要根据用户不同的配置需求打印不同的的报价单。尝试写一段代码来呈现这个逻辑。
二.装饰器模式呈现代码:
`
class Quotation:
def show(self):
print('牛屁哄哄电脑公司装机报价单:')
print('-' * 20)
class HardwareConfiguration():
def __init__(self):
self._quotation = None
def set_quotation(self, quo):
self._quotation = quo
def show(self):
pass
class MainBoard(HardwareConfiguration):
def __init__(self):
super().__init__()
def show(self):
self._quotation.show()
print('技嘉Giga 9AP-TX: 1000')
class Memory(HardwareConfiguration):
def __init__(self):
super().__init__()
def show(self):
self._quotation.show()
print('KingSton 8G : 800')
class CPU(HardwareConfiguration):
def __init__(self):
super().__init__()
def show(self):
self._quotation.show()
print('AMD 32Core : 800')
class DisplayAdaper(HardwareConfiguration):
def __init__(self):
super().__init__()
def show(self):
self._quotation.show()
print('ATI XXXX : 1200')
class Printer(HardwareConfiguration):
def __init__(self):
super().__init__()
def show(self):
self._quotation.show()
print('Printer : 1000')
if __name__ == '__main__':
quo = Quotation()
cpu = CPU()
mem = Memory()
main_board = MainBoard()
printer = Printer()
#装饰过程1
cpu.set_quotation(quo)
mem.set_quotation(cpu)
main_board.set_quotation(mem)
main_board.show()
#装饰过程2
printer.set_quotation(quo)
main_board.set_quotation(printer)
cpu.set_quotation(main_board)
mem.set_quotation(cpu)
mem.show()
`
执行输出:
C:\Python36\python.exe D:/练习/设计模式复习/装饰器模式/decorator_rf.py
牛屁哄哄电脑公司装机报价单:
--------------------
AMD 32Core : 800
KingSton 8G : 800
技嘉Giga 9AP-TX: 1000
牛屁哄哄电脑公司装机报价单:
--------------------
Printer : 1000
技嘉Giga 9AP-TX: 1000
AMD 32Core : 800
KingSton 8G : 800
Process finished with exit code 0
分析:
Quotation是报价单基本内容打印。程序可以根据不同用户的不同PC配置需求,去跟Quotation对象去添加装饰。CPU,Memory…每一种硬件的对象都是一种装饰。这样每一种装饰类就可以独立变化,没有相互耦合。
三.总结:
1.装饰模式是为已有功能动态添加功能的一种方式。
2.当需要执行特殊行为时,客户端代码就可以在运行时根据需要有选择地,按顺序的使用装饰功能包装对象了。
3.有效的把类的核心职责和装饰功能分开,而且可以去除相关类中重负的装饰逻辑。