今日总结

装饰模式

用装饰模式模拟手机功能的升级过程:简单的手机接收来电时,会发出声音提醒主人;而JarPhone除了声音还能振动;更高级的手机除了声音、振动外,还有灯光闪烁提示。

类图:

 

 

package DecoratorPattern;

abstract  class  CellPhone {

    public abstract void receiveCall();

}

package DecoratorPattern;

public class SimplePhone extends CellPhone{

    @Override

    public void receiveCall() {

        System.out.println("声音提示");

    }

}

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();

    }

}

 

package DecoratorPattern;

public class JarPhone extends PhoneDecorator{

    public JarPhone(CellPhone phone) {

        super(phone);

    }

    public void receiveCall() {

        super.receiveCall();

        System.out.println("震动提示");

    }

}

 

 

package DecoratorPattern;

public class ComplexPhone extends PhoneDecorator{

 

    public ComplexPhone(CellPhone phone) {

        super(phone);

    }

    public void receiveCall() {

        super.receiveCall();

        System.out.println("灯光闪烁提示");

    }

}

 

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();

    }

}

 

 

 

 

 

posted @ 2021-10-05 19:26  一条快乐的小鲸鱼  阅读(72)  评论(0编辑  收藏  举报