动态给一个对象添加一些额外的职责。使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。
通过采用组合、而非继承,Decorator模式实现了在运行时动态的扩展对象功能的能力,而且可以根据需要扩展多个功能。避免了单独使用继承带来的灵活性差和多子类衍生问题。
Component类在Decorator模式中充当抽象接口的角色,不应该去实现具体的行为。而且Decorator类对于Component类应该透明——换言之Component类无需知道Decorator类,Decorator类是从外部来扩展Component类的功能。
Decorator类在接口上表现为is-a Component的继承关系,即Decorator类继承了Component类所具有的接口。但在实现上又表现为has-a Component的组合关系,即Decorator类又使用了另外一个Component类。我们可以使用一个或多个Decorator对象来装饰一个 Component对象,且装饰后的对象仍然是一个Component对象。
[img]http://dl.iteye.com/upload/attachment/200445/a4db1401-93f9-3e5b-b3ec-db940251d4ec.jpg[/img]
Component类源码:
ConcreteComponent类源码:
Decorator类源码:
ConcreteDecoratorA类源码:
ConcreteDecoratorB类源码:
Client类源码:
原文:http://chenjumin.iteye.com/blog/582951
通过采用组合、而非继承,Decorator模式实现了在运行时动态的扩展对象功能的能力,而且可以根据需要扩展多个功能。避免了单独使用继承带来的灵活性差和多子类衍生问题。
Component类在Decorator模式中充当抽象接口的角色,不应该去实现具体的行为。而且Decorator类对于Component类应该透明——换言之Component类无需知道Decorator类,Decorator类是从外部来扩展Component类的功能。
Decorator类在接口上表现为is-a Component的继承关系,即Decorator类继承了Component类所具有的接口。但在实现上又表现为has-a Component的组合关系,即Decorator类又使用了另外一个Component类。我们可以使用一个或多个Decorator对象来装饰一个 Component对象,且装饰后的对象仍然是一个Component对象。
[img]http://dl.iteye.com/upload/attachment/200445/a4db1401-93f9-3e5b-b3ec-db940251d4ec.jpg[/img]
Component类源码:
public interface Component {
public void operation();
}
ConcreteComponent类源码:
public class ConcreteComponent implements Component {
public void operation(){
System.out.println("ConcreteComponent");
}
}
Decorator类源码:
public abstract class Decorator implements Component {
private Component component;
public Decorator(Component component){
this.component = component;
}
public void operation(){
component.operation();
}
}
ConcreteDecoratorA类源码:
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component){
super(component);
}
public void operation(){
super.operation();
this.newMethod();
}
public void newMethod(){
System.out.println("ConcreteDecoratorA: new method");
}
}
ConcreteDecoratorB类源码:
public class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component){
super(component);
}
public void operation(){
super.operation();
this.newMethod();
}
public void newMethod(){
System.out.println("ConcreteDecoratorB: new method");
}
}
Client类源码:
public class Client {
public static void main(String[] args) {
Component comp = new ConcreteComponent();
ConcreteDecoratorA da = new ConcreteDecoratorA(comp);
da.operation();
ConcreteDecoratorB db = new ConcreteDecoratorB(comp);
db.operation();
}
}
原文:http://chenjumin.iteye.com/blog/582951