装饰者模式

  1. 装饰角色抽象类或接口
public abstract class AbstractSubject  {
 protected  abstract void doSomething();
}
  1. 装饰角色抽象类或接口实现类
public class ConcreteSubject extends AbstractSubject {
    @Override
    protected void doSomething() {
        //具体操作
    }
}
  1. 装饰类抽象类
public class AbstractDecorator extends AbstractSubject{
    //待装饰的角色
    private AbstractSubject subject;
    //构造函数传递待装饰的角色
    public AbstractDecorator(AbstractSubject subject) {
        this.subject = subject;
    }
    @Override
    protected void doSomething() {
        this.subject.doSomething();
    }
}
  1. 装饰类抽象类具体实现类
public class ConcreteDecorator extends AbstractDecorator {
    public ConcreteDecorator(AbstractSubject subject) {
        super(subject);
    }
    @Override
    protected void doSomething() {
        super.doSomething();
        this.decorator();
    }
    private void decorator() {
        //装饰类方法
    }
}
  1. 场景使用
    //被装饰对象
    AbstractSubject subject = new ConcreteSubject();
    //装饰后对象
    AbstractDecorator decorator = new ConcreteDecorator(subject);
    //装饰后方法调用
    decorator.doSomething();

你可能感兴趣的:(装饰者模式)