一、定义:动态的给一个对象添加一些额外的职责。就增加功能来说,装饰模式相比生成子类更为灵活。Attach additional responsibilites to an object dynamically keeping the same interface. Decorators provide a flexible alternativer to subclass for extending functionallity.
装饰模式在不改变原有类的情况下,继续给该类添加职责,使得装饰后的类,更加适应业务需要。
二、简单代码示例
基础类:
public interface Component {
void buildWall();
}
public class BuildTheGrateWall implements Component { @Override public void buildWall() { // TODO Auto-generated method stub System.out.println("我要调用百万贫民,为我建造万里长城"); } }
装饰类:输出:public class DecoratorWall implements Component { private Component component; public DecoratorWall(BuildTheGrateWall buildTheGrateWall) { // TODO Auto-generated constructor stub this.component = buildTheGrateWall; } @Override public void buildWall() { // TODO Auto-generated method stub selfIntroduction(); //在调用基础类方法之前,添加职责 component.buildWall(); //不管基类怎么变化,都与我没有关系 afterBuild(); //调用基础类方法之后,添加职责 } private void selfIntroduction() { System.out.println("My name is YinZheng, I am the first tyrant of China, this is my dynasty. I want to" + " unified the China and nerver be invade again"); } private void afterBuild() { System.out.println("之后,我要派蒙恬北进,却匈奴七百余里,让胡人不敢南下木马,士不敢弯腰抱怨,君臣固守以安家业"); } }
My name is YinZheng, I am the first tyrant of China, this is my dynasty. I want to unified the China and nerver be invade again 我要调用百万贫民,为我建造万里长城 之后,我要派蒙恬北进,却匈奴七百余里,让胡人不敢南下木马,士不敢弯腰抱怨,君臣固守以安家业
总结:
装饰类和被装饰类可以独立发展,而不会互相耦合。装饰类是继承类的替代方案,用装饰类来代替子类去实现添加职责的行为,而不用暴漏基类给子类,比使用。子类更加灵活。装饰各过程中,避免多层装饰,一层一层的装饰提高了系统的复杂度。