装饰者模式
Decorator模式(别名Wrapper):动态将职责附加到对象上,若要扩展功能,装饰者提供了比继承更具弹性的代替方案。
意图:
动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。
设计原则:
1. 多用组合,少用继承。
利用继承设计子类的行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为。然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态地进行扩展。
2. 类应设计的对扩展开放,对修改关闭。
要点:
1. 装饰者和被装饰对象有相同的超类型。
2. 可以用一个或多个装饰者包装一个对象。
3. 装饰者可以在所委托被装饰者的行为之前或之后,加上自己的行为,以达到特定的目的。
4. 对象可以在任何时候被装饰,所以可以在运行时动态的,不限量的用你喜欢的装饰者来装饰对象。
5. 装饰模式中使用继承的关键是想达到装饰者和被装饰对象的类型匹配,而不是获得其行为。
6. 装饰者一般对组件的客户是透明的,除非客户程序依赖于组件的具体类型。在实际项目中可以根据需要为装饰者添加新的行为,做到“半透明”装饰者。
7. 适配器模式的用意是改变对象的接口而不一定改变对象的性能,而装饰模式的用意是保持接口并增加对象的职责。
实现原理:
具体实现举例:
1、存在一个MyComponent接口,其中有一个方法实现控制台打印功能;
public interface MyComponent {
public void printMsessage();
}
2、MyComponent的一个具体实现;
public class MyPrintComponent implements MyComponent {
public void printMsessage() {
System.out.println("myComponentImpl has done!");
}
}
3、现在对上述的实现类进行修饰,首先定义一个修饰类MyDecorator ,这个类实现了相同的接口并持有对MyComponent的引用;
public class MyDecorator implements MyComponent {
private MyComponent myComponent;
public void setMyComponent(MyComponent myComponent) {
this.myComponent = myComponent;
}
public void printMsessage() {
this.myComponent.printMsessage();
}
}
4、对MyPrintComponent的具体修饰类,在这个修饰类中对MyDecorator持有的MyComponent引用赋值,指向要修饰的具体的类;
public class MyPrintDecorator extends MyDecorator {
public MyPrintDecorator(){
super.setMyComponent(new MyPrintComponent());
}
public void printMsessage(){
this.beforeBehavior();
super.printMsessage();
this.afterBehavior();
}
private void beforeBehavior(){
System.out.println("MyPrintDecorator is start!");
}
private void afterBehavior(){
System.out.println("MyPrintDecorator is end!");
}
}
5、测试代码
public class TestDecorator {
public static void main(String[] args) {
//不使用修饰类
MyPrintComponent print1 = new MyPrintComponent();
print1.printMsessage();
System.out.println("\nuse decotator, then\n");
//使用修饰类
MyPrintDecorator print2 = new MyPrintDecorator();
print2.printMsessage();
}
}
输出的结果为:
myComponentImpl has done!
use decotator, then
MyPrintDecorator is start!
myComponentImpl has done!
MyPrintDecorator is end!
至此,本文对装饰模式的基本原理进行了基本的实现,从实际应用加深了对修饰模式的理解!
参考:http://www.cnblogs.com/god_bless_you/archive/2010/06/10/1755212.html