软件设计-Tutorial11
[实验任务一]:手机功能的升级
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
```mermaid classDiagram class Phone { <<interface>> +receiveCall() } class SimplePhone { +receiveCall() } class PhoneDecorator { <<abstract>> #phone: Phone +PhoneDecorator(phone: Phone) +receiveCall() } class JarPhone { +JarPhone(phone: Phone) +receiveCall() } class ComplexPhone { +ComplexPhone(phone: Phone) +receiveCall() } class PhoneTest { +main(args: String[]) } Phone <|.. SimplePhone : implements Phone <|.. PhoneDecorator : implements PhoneDecorator <|-- JarPhone : extends PhoneDecorator <|-- ComplexPhone : extends PhoneDecorator o-- Phone : has PhoneTest ..> Phone : uses PhoneTest ..> SimplePhone : uses PhoneTest ..> JarPhone : uses PhoneTest ..> ComplexPhone : uses ```
package Tutorial11; public interface Phone { void receiveCall(); // 接收来电 }
package Tutorial11; abstract public class PhoneDecorator implements Phone{ protected Phone phone; // 被装饰的手机 public PhoneDecorator(Phone phone) { this.phone = phone; } @Override public void receiveCall() { phone.receiveCall(); // 调用被装饰对象的功能 } }
package Tutorial11; public class SimplePhone implements Phone{ @Override public void receiveCall() { System.out.println("手机响铃:来电提醒!"); } }
package Tutorial11; public class JarPhone extends PhoneDecorator{ public JarPhone(Phone phone) { super(phone); } @Override public void receiveCall() { super.receiveCall(); // 调用父类的功能(响铃) System.out.println("手机震动:振动提醒!"); } }
package Tutorial11; public class ComplexPhone extends PhoneDecorator{ public ComplexPhone(Phone phone) { super(phone); } @Override public void receiveCall() { super.receiveCall(); // 调用父类的功能(响铃和振动) System.out.println("手机闪光:灯光闪烁提醒!"); } }
package Tutorial11; public class PhoneTest { public static void main(String[] args) { // 创建基础手机(SimplePhone) Phone simplePhone = new SimplePhone(); simplePhone.receiveCall(); // 只有响铃提醒 System.out.println("---------- 升级为JarPhone ----------"); // 创建升级后的手机(JarPhone,具有响铃和振动功能) Phone jarPhone = new JarPhone(simplePhone); jarPhone.receiveCall(); // 响铃 + 振动提醒 System.out.println("---------- 升级为ComplexPhone ----------"); // 创建最终版本的手机(ComplexPhone,具有响铃、振动和闪光功能) Phone complexPhone = new ComplexPhone(jarPhone); complexPhone.receiveCall(); // 响铃 + 振动 + 闪光提醒 } }