设计模式中的装饰模式介绍

 

装饰模式顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例

现在来举个例子介绍下:

  首先创建一个接口Sourceable;

  public interface Sourceable{

    public void method();

  }

  然后创建一个实现类Source,去实现这个接口

  public class Source implements Sourceable{

    public void method(){

      System.out.println("我是被装饰的类!"); 

    }

  }

  现在创建一个装饰类Decorator,也去实现接口

  public class Decorator  implements Sourceable{

     private Sourceable source;

     public Decorator(Sourceable source) {

      this.source = source;

    }

    public void method(){

      System.out.println("我在装饰头部!");

      source.method();

      System.out.println("我在装饰尾部!");

    }

  }

最后我们建一个测试类进行测试DecoratorTest

  public class DecoratorTest{

    Sourceable source = new Source();

    Decorator dd = new Decorator(source);

    dd.method();

  }

输出的内容是:

我在装饰头部!

我是被装饰的类!

我在装饰尾部!

 

 

装饰器模式的应用场景:

1、需要扩展一个类的功能。

2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)

缺点:产生过多相似的对象,不易排错!

 

posted on 2016-08-23 12:41  罗苏  阅读(170)  评论(0编辑  收藏  举报