设计模式笔记——Decorator
装饰模式Decorator
动态地给一个对象增加额外的职责,就增加功能来说,装饰模式比生成子类更灵活。

装饰模式视为已经有的功能动态地添加多更多的功能的一种方式。它把要装饰的功能单独封装在一个类里面,并让这个类封装它要装饰的对象,这样就可以为原有的对象增加新的功能,从而不会因为功能的扩展增加了竹类的复杂度。当需要执行特殊行为时,用户可以选择的使用装饰功能包含的对象。
有效的把类的核心职责和装饰功能分开,除掉了类中重复的装饰修饰。
package decorator.pattern;
public class DecoratorPattern {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ConcreteCompoment compoment=new ConcreteCompoment();
ConcreteDecoratorA decoratorA=new ConcreteDecoratorA();
ConcreteDecoratorB decoratorB=new ConcreteDecoratorB();
decoratorA.SetCompoment(compoment);
decoratorB.SetCompoment(decoratorA);
decoratorB.Operation();
}
}
package decorator.pattern;
public interface Compoment {
public void Operation();
}
package decorator.pattern;
public class ConcreteCompoment implements Compoment {
@Override
public void Operation() {
// TODO Auto-generated method stub
System.out.println("Concrete Compoment Operation");
}
}
package decorator.pattern;
public class Decorator implements Compoment {
protected Compoment compoment;
public void SetCompoment(Compoment compoment) {
this.compoment = compoment;
}
@Override
public void Operation() {
// TODO Auto-generated method stub
if (compoment != null)
compoment.Operation();
}
}
package decorator.pattern;
public class ConcreteDecoratorB extends Decorator {
private String state;
@Override
public void Operation() {
// TODO Auto-generated method stub
super.Operation();
setState("stateB");
System.out.println("ConcreteDecoratorB Operation");
}
private void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
}
package decorator.pattern;
public class ConcreteDecoratorA extends Decorator {
private String state;
@Override
public void Operation() {
// TODO Auto-generated method stub
super.Operation();
setState("stateA");
System.out.println("ConcreteDecoratorA Operation");
}
private void setState(String state) {
this.state = state;
}
public String getState() {
return state;
}
}

浙公网安备 33010602011771号