1.裝飾器模式的定義
動態地給一個對象添加一些額外的職責。就增加功能來說,裝飾模式比生成子類更爲靈活
2.裝飾器模式的UML圖
Component:組件對象的接口,可以給這些對象動態的添加職責
ConcreteComponent:具體的組件對象,實現組件對象接口,通常就是被裝飾器裝飾的原始對象,也就是可以給這個對象添加職責
Decorator:所有裝飾器的抽象父類,需要定義一個與組件接口一致的接口,並持有一個Component對象,其實就是持有一個被裝飾的對象
3.代碼實現
public abstract class Component
{
public void operation();
}
public class ConcreteComponent extends Component{
public void operation(){
}
}
public abstract class Decorator extends Component
{
protected Component component;
public Decorator(Component component){
this.component=component;
}
public void operation(){
this.component.operation();
}
}
public class ConcreteDecoratorA extends Decorator
{
private String addedState;
public String getAddedState(){
return this.addedState;
}
public void setAddedState(String addedState){
this.addedState=addedState;
}
public ConcreteDecoratorA(Component component){
this.component=component;
}
public void operation(){
this.component=compnent;
}
}
public class ConcreteDecoratorB extends Decorator
{
private String addedState;
public String getAddedState(){
return this.addedState;
}
public void setAddedState(String addedState){
this.addedState=addedState;
}
public ConcreteDecoratorB(Component component){
this.component=component;
}
public void operation(){
this.component=compnent;
}
}
public class Client
{
public static void main(String[] args){
Component component=new ConreteComponent();
Decorator decorator=new ConcreteDecoratorA(component);
decorator.operation();
}
}
4.裝飾模式的本質:動態組合