装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。动态地给一个对象添加一些额外的职责。就增加功能来说,装饰器模式相比生成子类更为灵活。装饰器模式就是用来增强功能。和代理模式有些相似。
public interface Subject { public void doSomething() ; }
public class RealSubject implements Subject { //具体业务 @Override public void doSomething() { System.out.println("RealSubject 执行具体业务"); } }
public abstract class SubjectDecorator { private Subject subject; SubjectDecorator(Subject subject) { this.subject = subject; } public void doSomething(){ subject.doSomething(); this.doOtherthing(); } protected abstract void doOtherthing(); }
public class RealSubejctDecorator extends SubjectDecorator { RealSubejctDecorator(Subject subject) { super(subject); } @Override public void doOtherthing() { System.out.println("RealSubejctDecorator -- doOtherthing"); } }
public class Client { public static void main(String[] args) { Subject realSubject = new RealSubject() ; RealSubejctDecorator realSubejctDecorator = new RealSubejctDecorator(realSubject) ; realSubejctDecorator.doSomething(); } }