装饰模式(转)

装饰模式是对对象功能增强时,平时使用继承的一种替代方案
一.UML示意图:

二.组成部分:
1. 抽象构件:原始的功能接口
2. 具体构件:具体的原始功能类
3. 装饰角色:持有具体构件类的对象,以便执行原有功能
4. 具体装饰:具体扩展的功能在这里
三.例子代码:使用装饰模式来演示一个对”行走”功能扩展的例子(听音乐+行走和唱歌+行走)
1. 抽象构件
package com.eekq.decorator;

publicinterface Component {
/**原始接口*/
publicvoid go();
}
2. 具体构件
package com.eekq.decorator;

publicclass ConcreteComponent implements Component {

publicvoid go() {
System.out.println("行走");
}

}
3.装饰角色来了
package com.eekq.decorator;

publicclass Decorator implements Component {
/**持有私有的原始构件*/
private Component component;

/**构造子,委派给原始构件*/
protected Decorator(Component component) {
this.component = component;
}

/**调用原始构件功能,通常就可直接把扩展功能加在此方法中*/
publicvoid go() {
this.component.go();
}

}
4.具体装饰(这里演示了两种扩展的情况,走路+听音乐和唱歌s)
(1).
package com.eekq.decorator;

publicclass ConcreteDecoratorListen extends Decorator {

/**构造子,相关初始化*/
public ConcreteDecoratorListen(Component component) {
super(component);
// code is here
}

/**商业逻辑,对原始构件功能的扩展*/
publicvoid go() {
listen("听音乐");//执行扩展功能
super.go();
}

privatevoid listen(Object obj){
System.out.println(obj);
}

}
(2).
package com.eekq.decorator;

publicclass ConcreteDecoratorSing extends Decorator {

/**构造子,相关初始化*/
public ConcreteDecoratorSing(Component component) {
super(component);
// code is here
}

/**商业逻辑,对原始构件功能的扩展*/
publicvoid go() {
super.go();
System.out.println(sing());;// 执行扩展功能
}

private String sing() {
return"唱歌";
}
}
5.客户端调用
package com.eekq.decorator;

publicclass Main {

publicstaticvoid main(String[] args) {
/**原始构件*/
Component component = new ConcreteComponent();
/**边听音乐,边走路*/
ConcreteDecoratorListen cdl = new ConcreteDecoratorListen(component);
cdl.go();
System.out.println();
/**边走路,边唱歌*/
ConcreteDecoratorSing cds = new ConcreteDecoratorSing(component);
cds.go();
}

}
四.总结
优点:装饰模式和继承都是对功能的扩展,而装饰模式使用的是组合,可以不用继承而达到这一效果.使用过多的继承会增加系统的复杂性和偶合性
缺点:装饰模式要产生一些辅助性的对象,但这些对象看上去都比较像,不是很容易检查(好的命名应该是提高检查的一个办法)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值