concept

Dynamically extend the functionality of objects in a way that is transparent to the client (an alternative to inheritance, which is more flexible than inheritance). Typically used in scenarios that require dynamic extension of class functionality.

implementation

  • Component — Abstract Component, the original object of the modified object
  • ConcreteComponent – The modified object
  • Decorator — The abstract Decorator class inherits the abstract Component and holds a reference to the original Component.
  • ConcreteDecorator – ConcreteDecorator class for adding new functionality.
public abstract class Component {
    public abstract void fun();
}

public class ConcreteComponent extends Component {
    @Override
    public void fun(){
        System.out.println("ok");
    }
}

public abstract class Decorator extends Component {
    private Component component;

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

    @Override
    public void fun(){
        component.fun();
    }
}

public class ConcretDecorator extends Decorator{
    public ConcretDecorator(Component c){
        super(c);
    }

    @Override
    public void fun(){
        fun1();
        super.fun();
        fun2();
    }

    public void fun1(){
        System.out.println("1");
    }

    public void fun2(){
        System.out.println("2"); }}Copy the code