decorate装饰模式

 

package com.decorate;

public class Iphone implements Phone{

    @Override
    public void call() {
        System.out.println("手机可以打电话");
    }


}
package com.decorate;

public interface Phone{
    public void call();//打电话
}
package com.decorate;

public abstract class PhoneDecorate implements Phone{
    private Phone p;
    
    public PhoneDecorate(Phone p){
        this.p=p;
    }
    @Override
    public void call() {
        this.p.call();
    }
}
package com.decorate;

public class MusicPhoneDecorate extends PhoneDecorate {

    public MusicPhoneDecorate(Phone p) {
        super(p);
    }
    @Override
    public void call() {
        super.call();
        System.out.println("手机可以听音乐");
    }

}
package com.decorate;

public class RingPhoneDecorate extends PhoneDecorate {

    public RingPhoneDecorate(Phone p) {
        super(p);
    }
    
    @Override
    public void call() {
        System.out.println("手机可以听彩铃");
        super.call();
    }

}
package com.decorate;

public class PhoneDemo {
    public static void main(String[] args) {
        Iphone iphone=new Iphone();
        iphone.call();
        System.out.println("---");
        //接电话前听彩铃
        PhoneDecorate pd=new RingPhoneDecorate(iphone);
        pd.call();
        System.out.println();
        //接电话后听音乐
        pd=new MusicPhoneDecorate(iphone);
        pd.call();
        System.out.println("-----");
        //手机在接听前听彩铃,接听后听音乐
        pd=new MusicPhoneDecorate(new RingPhoneDecorate(iphone));
        pd.call();
    }
}

 

posted @ 2016-06-23 07:13  guodaxia  阅读(307)  评论(0编辑  收藏  举报