2024/11/07
软件设计 实验11:装饰模式
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
public interface XiaoMi { public void voice(); } public class SimpleXiaoMi implements XiaoMi{ @Override public void voice() { System.out.println("发出声音!"); } } public class XiaoMiDecorator implements XiaoMi{ private XiaoMi xiaomi; public XiaoMiDecorator(XiaoMi p) { this.xiaomi=p; } public void voice() { System.out.println("发出声音"); } } public class JarXiaoMi extends XiaoMiDecorator{ public JarXiaoMi(XiaoMi xiaomi) { super(xiaomi); System.out.println("complex xiaomi"); } public void vibrate () { System.out.println("震动"); } } public class ComplexXiaoMi extends XiaoMiDecorator{ public ComplexXiaoMi(XiaoMi xiaomi) { super(xiaomi); System.out.println("complex xiaomi"); } public void vibrate () { System.out.println("震动"); } public void flash(){ System.out.println("闪光灯"); } } public static void main( String[] args ) { XiaoMi phone = new SimpleXiaoMi(); phone.voice(); // 输出 "发出声音!" JarXiaoMi jarPhone = new JarXiaoMi(phone); jarPhone.voice(); // 输出 "发出声音" jarPhone.vibrate(); // 输出 "震动" ComplexXiaoMi complexPhone = new ComplexXiaoMi(phone); complexPhone.voice(); // 输出 "发出声音" complexPhone.vibrate(); // 输出 "震动" complexPhone.flash(); // 输出 "闪光灯" }
运行实例: