装饰模式——java实现
问题描述;
用装饰模式模拟手机功能的升级过程:简单的手机(SimplePhone)在接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机(ComplexPhone)除了声音、振动外,还有灯光闪烁提示。
类图:
运行截图:
代码:
//Phone.java package shiyan11; public interface Phone { public void call(); } //SimplePhone.java package shiyan11; public class SimplePhone implements Phone{ public SimplePhone(){ System.out.println("手机收到来电"); } public void call(){ System.out.println("发出声音:主人来电话啦!"); } } //UpgradePhone.java package shiyan11; public class UpgradePhone implements Phone{ private Phone phone; public UpgradePhone(Phone a){ phone=a; } public void call(){ phone.call(); } } //JarPhone.java package shiyan11; public class JarPhone extends UpgradePhone{ public JarPhone(Phone phone){ super(phone); System.out.println("***增加振动的功能***"); } public void shoke(){ System.out.println("振动:嗡嗡嗡"); } } //ComplexPhone.java package shiyan11; public class ComplexPhone extends UpgradePhone{ public ComplexPhone(Phone phone){ super(phone); System.out.println("***增加闪光功能***"); } public void light(){ System.out.println("灯光闪烁:咔嚓"); } }