[實驗任務一]:手機功能的升級
用裝飾模式模擬手機功能的升級過程:簡單的手機(SimplePhone)在接收來電時,會發出聲音提醒主人;而JarPhone除了聲音還能振動;更高階的手機(ComplexPhone)除了聲音、振動外,還有燈光閃爍提示。
實驗要求:
1.提交類圖;
2.提交原始碼;
package test11; public abstract class Phone { public void serviceCall() { } } package test11; public class ComplexPhone extends PhoneDecoration { public ComplexPhone(Phone phone) { super(phone); } @Override public void serviceCall() { super.serviceCall(); System.out.println("ComplexPhone:發出聲音、震動並燈光閃爍提醒主人電話來了"); } } package test11; public class PhoneDecoration extends Phone { private Phone phone = null; public PhoneDecoration(Phone phone) { if (phone != null) { this.phone = phone; } else { this.phone = new SimplePhone(); } } @Override public void serviceCall() { phone.serviceCall(); } } package test11; public class Client { public static void main(String[] args) { Phone p1 = new SimplePhone(); System.out.println("生產簡單手機"); p1.serviceCall(); System.out.println("***********************"); Phone p2 = new JarPhone(p1); System.out.println("升級為JarPhone手機"); p2.serviceCall(); System.out.println("***********************"); Phone p3 = new ComplexPhone(p2); System.out.println("升級為ComplexPhone手機"); p3.serviceCall(); } } package test11; public class JarPhone extends PhoneDecoration { public JarPhone(Phone phone) { super(phone); } @Override public void serviceCall() { super.serviceCall(); System.out.println("JarPhone:發出聲音並震動提醒主人電話來了"); } } package test11; public class SimplePhone extends Phone { public void serviceCall() { System.out.println("SimplePhone:發出聲音提醒主人電話來了"); } }