装饰器[Decorator]模式

装饰器[Decorator]模式

模式定义:在不改变原有对象的基础上,将功能附加到对象上。

符合开闭原则

应用场景:扩展一个类的功能或者给一个类添加附加职责

优点:

  • 1:不改变原有对象的情况下给一个对象添加功能
  • 2: 使用不同的组合可以实现不同的效果
  • 3:符合开闭原则

java代码:

public class DecoratorTest {

    public static void main(String[] args) {


        Component component = new ConcreteComponent();
        component.operation();
        System.out.println("------------------------");
        ConcreteDecorator1 concreteDecorator1 = new ConcreteDecorator1(component);
        concreteDecorator1.operation();
        System.out.println("-----------------------");

        //test 装饰者2
        ConcreteDecorator2 concreteDecorator2 = new ConcreteDecorator2(new ConcreteDecorator1(new ConcreteComponent()));
        concreteDecorator2.operation();
    }
}


interface Component{

    void operation();
}

class ConcreteComponent implements Component{

    @Override
    public void operation() {
        System.out.println("拍照");
    }
}

//装饰者类
abstract  class Decorator implements  Component{

    Component component;

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

}

//装饰者1
class ConcreteDecorator1 extends Decorator{

    //构造方法
    public ConcreteDecorator1(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("添加美颜");
        component.operation();
    }


}

//装饰者2
class ConcreteDecorator2 extends Decorator{

    public ConcreteDecorator2(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("实现滤镜");
        component.operation();
    }
}

源码:

javax.servlet.http.HttpServletRequestWrapper
posted @ 2020-07-31 15:31  Noob52037  阅读(111)  评论(0编辑  收藏  举报