装饰模式就像我们穿衣服一样,先穿什么、然后在穿什么。它的意思就是说动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更加灵活。
装饰模式的结构图如下:
Component类:
package com.kunl.decorator;
/**
* @author fokman
* @version 1.0
* @created 29-五月-2011 22:57:05
*/
public abstract class Component {
public abstract void operation();
}
具体对象ConcreteComponent类:
package com.kunl.decorator;
/**
* @author fokman
* @version 1.0
* @created 29-五月-2011 22:57:05
*/
public class ConcreteComponent extends Component {
public void operation(){
System.out.println("具体对象的操作");
}
}
装饰抽象类Decorator:
package com.kunl.decorator;
/**
* @author fokman
* @version 1.0
* @created 29-五月-2011 22:57:06
*/
public abstract class Decorator extends Component {
public Component component;
public void setComponent(Component component) {
this.component = component;
}
public void operation(){
if(component!=null){
component.operation();
}
}
}
具体装饰对象A ConcreteDecoratorA类:
package com.kunl.decorator;
/**
* @author fokman
* @version 1.0
* @created 29-五月-2011 22:57:06
*/
public class ConcreteDecoratorA extends Decorator {
private String addedState;
public void setAddedState(String addedState) {
this.addedState = addedState;
}
public String getAddedState() {
return addedState;
}
public void operation() {
super.operation();
setAddedState("new state");
System.out.println("具体装饰对象A");
}
}
具体装饰对象B ConcreteDecoratorB类:
package com.kunl.decorator;
/**
* @author fokman
* @version 1.0
* @created 29-五月-2011 22:57:06
*/
public class ConcreteDecoratorB extends Decorator {
public void operation(){
super.operation();
addedBehavior();//
System.out.println("装饰对象B");
}
private void addedBehavior(){
System.out.println("执行装饰对象B");
}
}
总结:装饰模式是为已有功能动态的添加更多功能的一种方式。当系统需要新功能的时候,是向旧的类添加新的代码。这些新的代码通常装饰了原有类的核心职责或主要行为,把类中的装饰功能从类中搬移去除,这样就可以简化原有的类。