实验11:装饰模式
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
1. 提交类图;
2.提交源代码;
Phone.java
// 定义手机接口 interface Phone { String receiveCall(); }
SimplePhone.java
// 实现基础的SimplePhone类 class SimplePhone implements Phone { @Override public String receiveCall() { return "SimplePhone: 发出声音提醒主人"; } }
JarPhone.java
// 实现具有振动功能的JarPhone类 class JarPhone implements Phone { @Override public String receiveCall() { return "JarPhone: 发出声音提醒主人, 并振动"; } }
ComplexPhone.java
// 实现具有振动和灯光闪烁功能的ComplexPhone类 class ComplexPhone implements Phone { @Override public String receiveCall() { return "ComplexPhone: 发出声音提醒主人, 并振动, 并灯光闪烁提示"; } }
Main.java
public class Main { public static void main(String[] args) { // 创建不同手机类型的实例 Phone simplePhone = new SimplePhone(); Phone jarPhone = new JarPhone(); Phone complexPhone = new ComplexPhone(); // 模拟接收来电 System.out.println("生产简单手机"); System.out.println(simplePhone.receiveCall()); System.out.println("---------------------"); System.out.println("升级手机为JarPhone"); System.out.println(simplePhone.receiveCall()); System.out.println(jarPhone.receiveCall()); System.out.println("---------------------"); System.out.println("升级手机为ComplexPhone"); System.out.println(simplePhone.receiveCall()); System.out.println(jarPhone.receiveCall()); System.out.println(complexPhone.receiveCall()); } }
标签:receiveCall,JarPhone,报告,System,Phone,println,今日,out From: https://www.cnblogs.com/zjq164/p/17818949.html