前言:继承是实现类复用的重要手段,但却不是惟一的手段,经过类的关联组合一样能够作到,并且若是使用得当比经过继承更富有弹性。“装饰器模式”就是经过组合来实现相似复用和包装,这就是OO设计的另外一个原则“合成复用原则”:则是尽可能使用合成/聚合的方式,而不是使用继承。设计模式
概念:容许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是做为现有的类的一个包装。ide
代码实现: 测试
1.Component:定义一个对象接口,能够给这些对象动态地添加职责。this
2.ConcreteComponent: 定义一个对象,能够给这个对象添加一些职责。spa
3.Decorator: 维持一个指向 Component 对象的指针,并定义一个与 Component 接口一致的接口。设计
4.ConcreteDecorator:向组件添加职责。代理
public interface Component { void method(); } public class ConcreteComponent implements Component { @Override public void method() { System.out.println("this is old method"); } } public class Decorator implements Component { private Component component; public Decorator(Component component) { this.component = component; } @Override public void method() {
//方法先后装饰 System.out.println("before method,Decorator doing "); component.method(); System.out.println("after method ,Decorator doing"); } } //测试代码 public static void main(String[] args) { Decorator decorator = new Decorator(new ConcreteComponent()); decorator.method(); }
总结:指针
其实装饰器模式和代理模式很像,上面的代码就和静态代理同样(我的理解),只是目的不同而已,一个用于代理,一个用于装饰,就好像武侠的打斗现场没人手里都有一把剑,有人拿来杀人,有人拿来救人,不必纠结他们的区别。学会灵活使用就好了。code
优势:能够动态扩展一个对象的功能。component
缺点:类太多,继承结构复杂。