装饰模式-java
package u11; public class ComplexPhone extends Changer{ public ComplexPhone(Phone phone) { super(phone); System.out.println("变成高级手机"); flash(); } public void flash() { System.out.println("手机来电闪烁灯光提示"); } }
package u11; public final class JarPhone extends Changer{
package u11; public abstract class Phone { public abstract void voice(); }
package u11; public class SimplePhone extends Phone{ public SimplePhone() { System.out.println("这是一部简单手机"); } @Override public void voice() { System.out.println("手机来电声音"); } }
public JarPhone(Phone phone) { super(phone); System.out.println("手机增加震动功能"); } public void voice() { super.voice(); System.out.println("来电震动"); } }
package u11; public class Changer extends Phone{ private Phone phone; public Changer(Phone phone) { this.phone=phone; } @Override public void voice() { phone.voice(); } }
package u11; public class Client { public static void main(String[] args) { //父类调用子类方法 Phone p1=new SimplePhone(); p1.voice(); System.out.println("===================="); Phone p2=new JarPhone(p1); p2.voice(); System.out.println("===================="); Phone p3=new ComplexPhone(p2); p3.voice(); } }