10.11
实验11:装饰模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解装饰模式的动机,掌握该模式的结构;
2、能够利用装饰模式解决实际问题。
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
实验要求:
1. 提交类图;
2. 提交源代码;
class SimplePhone:
def receiveCall(self):
print("Simple phone: Sound alert")
class PhoneDecorator:
def __init__(self, phone):
self.phone = phone
def receiveCall(self):
self.phone.receiveCall()
class VibrateDecorator(PhoneDecorator):
def receiveCall(self):
super().receiveCall()
print("Vibrating")
class LightDecorator(PhoneDecorator):
def receiveCall(self):
super().receiveCall()
print("Light flashing")
if __name__ == "__main__":
simple_phone = SimplePhone()
jar_phone = VibrateDecorator(simple_phone)
complex_phone = LightDecorator(jar_phone)
complex_phone.receiveCall()
3.注意编程规范。