标签:
今天讲下设计模式中的装饰设计模式,这个在我门的IO流已经使用到了,首先看下对装饰设计模式的定义
定义:
public interface Phone { public void call(); }具体某个电话的实现类
public class IPhone implements Phone { public IPhone() { super(); } @Override public void call() { System.out.println("打电话"); } }
public abstract class PhoneDecorator implements Phone { private Phone phone; public PhoneDecorator(Phone phone) { super(); this.phone = phone; } @Override public void call() { phone.call(); } }//彩铃具体装饰类的实现,并添加功能
public class RingDecorator extends PhoneDecorator { public RingDecorator(Phone phone) { super(phone); } @Override public void call() { System.out.println("我要手机可以听彩铃"); super.call(); } }//音乐具体装饰类的实现 并添加播放音乐的功能
public class MusicDecorate extends PhoneDecorator { public MusicDecorate(Phone phone) { super(phone); } @Override public void call() { super.call(); System.out.println("手机可以听音乐"); } }测试类
public class DecoratorTest { public static void main(String[] args) { Phone phone = new IPhone(); phone.call(); System.out.println("*************************"); PhoneDecorator pd = new RingDecorator(phone); pd.call(); System.out.println("*************************"); pd = new MusicDecorate(phone); pd.call(); System.out.println("*************************"); //现在是打电话之前有彩铃来了 挂断电话后可以听因为 pd = new MusicDecorate(new RingDecorator(phone)); pd.call(); } }结果:
标签:
原文地址:http://blog.csdn.net/coderinchina/article/details/42032167