装饰者模式(Decorator)

前言:继承是实现类复用的重要手段,但却不是唯一的手段,通过类的关联组合同样可以做到,而且如果使用得当比通过继承更富有弹性。“装饰器模式”就是通过组合来实现类似复用和包装,这就是OO设计的另一个原则“合成复用原则”:则是尽量使用合成/聚合的方式,而不是使用继承。

概念:允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。

     代码实现:       

     1.Component:定义一个对象接口,可以给这些对象动态地添加职责。

     2.ConcreteComponent: 定义一个对象,可以给这个对象添加一些职责。

     3.Decorator: 维持一个指向 Component 对象的指针,并定义一个与 Component 接口一致的接口。

     4.ConcreteDecorator:向组件添加职责。

 

public interface Component {

    void method();

}

public class ConcreteComponent implements Component {
    @Override
    public void method() {
        System.out.println("this is old method");
    }
}

public   class Decorator implements  Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void method() {
//方法前后装饰 System.out.println(
"before method,Decorator doing "); component.method(); System.out.println("after method ,Decorator doing"); } } //测试代码 public static void main(String[] args) { Decorator decorator = new Decorator(new ConcreteComponent()); decorator.method(); }

总结:

       其实装饰器模式和代理模式很像,上面的代码就和静态代理一样(个人理解),只是目的不一样而已,一个用于代理,一个用于装饰,就好像武侠的打斗现场没人手里都有一把剑,有人拿来杀人,有人拿来救人,没必要纠结他们的区别。学会灵活使用就行了。

       优点:可以动态扩展一个对象的功能。

       缺点:类太多,继承结构复杂。

posted @ 2019-08-09 14:06  Don'tYouSee  阅读(153)  评论(0)    收藏  举报