码迷,mamicode.com
首页 > 其他好文 > 详细

decorate装饰模式

时间:2016-06-23 07:42:08      阅读:294      评论:0      收藏:0      [点我收藏+]

标签:

 

技术分享

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

 

decorate装饰模式

标签:

原文地址:http://www.cnblogs.com/aigeileshei/p/5609213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!