简单理解,装饰模式是不更改原有的类,往这个类中动态添加新的功能。
结构如图:
按上图编写代码如下:
Component:
package cn.sasa.decorator; //定义一个接口 //为一些对象动态添加职责 public abstract class Component { public abstract void operation(); }
ConcreteComponent:
package cn.sasa.decorator; public class ConcreteComponent extends Component{ @Override public void operation() { System.out.println("具体对象的操作"); } }
Decorator:
package cn.sasa.decorator; public class Decorator extends Component{ protected Component component; public void SetComponent(Component component) { this.component = component; } @Override public void operation() { if(component!=null) { component.operation(); } } }
DecoratorA:
package cn.sasa.decorator; public class DecoratorA extends Decorator{ //本类独有的功能 private String state=""; public void operation() { super.operation(); state="A---hi~"; System.out.println("A功能:"+state); } }
DecoratorB:
package cn.sasa.decorator; public class DecoratorB extends Decorator{ public void operation() { super.operation(); action(); } //装饰B独有的方法 private void action() { System.out.println("B功能:B---hi~"); } }
测试类test:
package cn.sasa.decorator; public class test { public static void main(String[] args) { ConcreteComponent concre = new ConcreteComponent(); DecoratorA da = new DecoratorA(); DecoratorB db = new DecoratorB(); da.SetComponent(concre); db.SetComponent(da); db.operation(); } }
通过Decorator的setComponent()向需要装饰的具体类进行包装。每个装饰类只关注自己的功能,不需要关心如何被添加到对象链当中。