设计模式12——Decorator设计模式

Decorator装饰设计模式是动态给一个对象添加一些额外的职责,但同时又不影响对象本身已有的功能。

通常使用继承来实现功能的扩展,但是如果这些需要扩展的功能的种类很烦多,就会生成很多子类,增加系统复杂性。同时由于使用继承实现功能的扩展时,必须可预见这些扩展功能,这些功能是编译时就确定的了,是静态的。使用Decorator装饰设计模式就可以根据功能需要有用户动态决定加入的方式和时机,实现“即插即用”的功能,在运行时动态决定增加何种功能。

Decorator装饰设计模式中的两种角色:

Decoratee被装饰者:即需要功能增强的原始对象,即目标对象。

Decorator装饰者:为原始对象提供功能增强的对象。

装饰者模式UML图如下:


Java swing中的JTextArea组件默认没有滚动条和边框,我们使用Decorator装饰设计模式动态为其加上滚动条和边框,使用Decorator装饰设计模式例子实现的例子代码如下:

interface VisualComponent{
	public void draw();
}
//Decoratee
class TextArea implements VisualComponent {
	public void draw(){
	System.out.println(“Draw TextArea”);
}
}
//抽象Decorator
abstract class Decorator implements VisualComponent {
	protected VisualComponent component;
	public Decorator(VisualComponent component){
	this.component = component;
}
public void draw(){
	component.draw();
}
}
//滚动条Decorator
class ScrollDecorator extends Decorator{
	public ScrollDecorator (VisualComponent component){
	super(component);
}
public void draw(){
	super.draw();
	scrollTo();
}
public void scrollTo(){
	System.out.println(“TextArea scroll to…”);
}
}
//边框Decorator
class BorderDecorator extends Decorator{
	public BorderDecorator(VisualComponent component){
	super(component);
}
public void draw(){
	super.draw();
	drawBorder();
}
public void drawBorder (){
	System.out.println(“Draw border for TextArea …”);
}
}
public class DecoratorDemo{
	public static void main(String[] args){
	//画一个普通的TextArea
	TextArea textArea = new TextArea();
	textArea.draw();
	//画一个带滚动条的TextArea
	ScrollDecorator scroll = new ScrollDecorator(new TextArea());
	scroll.draw();
	//画一个带边框的TextArea
	BorderDecorator border = new BorderDecorator(new TextArea());
	border.draw();
	//画一个既带边框又带滚动条的TextArea
	BorderDecorator border2 = new BorderDecorator(new ScrollDecorator(new TextArea()));
	border2.draw();
}
}

Decorator装饰设计模式和Proxy代理模式的区别:

Decorator装饰设计模式和Proxy代理模式非常类似,都可以对目标对象做一些动态改变,以致于很多初学者分不清楚Decorator装饰设计模式和Proxy代理模式,个人觉得二者简单区别如下:

(1).Proxy代理模式中,客户端不直接调用服务端程序,而是通过一个代理对象来调用服务端程序,类似一个请求转发的作用。

(2). Decorator装饰设计模式中,被装饰对象可以不用添加任何装饰而直接使用,也可以通过装饰器的包装动态增强功能。

JDK中装饰者模式的应用:

java.io
java.util.Collections#synchronizedList (List)
AWT Swing 图形组件
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值