常用设计模式-装饰者模式
顾名思义,装饰者装饰者,肯定是对一件东西进行装饰。这里说的装饰就是对我们的类行为进行装饰;既然有装饰者,肯定有被装饰者;先看一下下面的一张图(画了半天类图没画明白)就用这个替代吧。
1.首先我们有一个公共行为接口,加入里面有方法A,装饰者,和被装饰者都需要实现这个接口;
2.装饰者是需要持有被装饰者的实例的
3.装饰者1装饰者2 需要继承装饰者,然后对方法进行增强操作。
接下来看代码:
接口
//公共行为的接口
public interface Component{
public void methodA();
}
被装饰者
//被装饰者类实现Component接口
public class ConcreteComponent implements Component{
public void methodA(){
System.out.println("方法A实现")
}
}
装饰者
//装饰者类实现Component接口
public class Decorator implements Component{
//持有被装饰者对象
protected Component component;
//构造方法
Decorator(Component component){
super();
this.component = component
}
//方法A实现
public void methodA(){
component.methodA();
System.out.println("装饰者对被装饰者的methodA()方法的增强")
}
}
扩展装饰
//扩展的装饰者继承装饰者Decorator类
public class DecoratorChild extends Decorator {
//持有被装饰者对象
protected Component component;
//构造方法直接调用父类
Decorator(Component component){
super(component);
}
//方法A实现
public void methodA(){
//如果你需要父类Decorator 的增强,直接调用super.methodA();
super.methodA();
//如果你不需要父类Decorator 的增强,注释掉上面一行,直接调用被装饰者的methodA()方法
component.methodA();
System.out.println("DecoratorChild 类在Decorator 基础之上再次对
对被装饰者的methodA()方法进行扩展增强")
}
}
总结:
装饰者模式定义:以装饰的方式,动态的将责任附加到对象上。
优点:在不改变具体类代码,动态叠加增强行为功能。而且,装饰者模式,提供了比继承更有弹性的扩展方案,你既可以使用父类的扩展,也可以自己实现扩展,动态的选择增强。