类图
源码
CellPhone.java package decoratorPattern; public abstract class CellPhone { public abstract void receiveCall(); } ComplexPhone.java package decoratorPattern; public class ComplexPhone extends PhoneDecorator{ public ComplexPhone(CellPhone phone) { super(phone); } public void receiveCall() { super.receiveCall(); System.out.println("灯光闪烁提示"); } } JarPhone.java package decoratorPattern; public class PhoneDecorator extends CellPhone{ private CellPhone phone=null; public PhoneDecorator(CellPhone phone) { if(phone!=null){ this.phone = phone; }else{ this.phone = new SimplePhone(); } } @Override public void receiveCall() { phone.receiveCall(); } } SimplePhone.java package decoratorPattern; public class SimplePhone extends CellPhone{ @Override public void receiveCall() { System.out.println("声音提示"); } } PhoneDecorator.java package decoratorPattern; public class PhoneDecorator extends CellPhone{ private CellPhone phone=null; public PhoneDecorator(CellPhone phone) { if(phone!=null){ this.phone = phone; }else{ this.phone = new SimplePhone(); } } @Override public void receiveCall() { phone.receiveCall(); } } Client.java package decoratorPattern; public class Client { public static void main(String a[]){ CellPhone p1 = new SimplePhone(); p1.receiveCall(); System.out.println(); CellPhone p2 = new JarPhone(p1); p2.receiveCall(); System.out.println(); CellPhone p3 = new ComplexPhone(p2); p3.receiveCall(); } }
测试截图