装饰模式(Decorator Pattern)(转)

动态给一个对象添加一些额外的职责。使用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类源码:
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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值