设计模式之装饰模式

定义:

装饰模式:动态地把一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
 
 
 
Component是定义一个对象接口,可以给这些对象动态地添加职责,ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的,至于ComcreateDecorator就是具体的装饰对象,祈祷给Component添加职责的功能。
 
 
 
 
 
在装饰模式中的各个角色有:
  (1)抽象构件(Component)角色:给出一个抽象接口,以规范准备接收附加责任的对象。
  (2)具体构件(Concrete Component)角色:定义一个将要接收附加责任的类。
  (3)装饰(Decorator)角色:持有一个构件(Component)对象的实例,并实现一个与抽象构件接口一致的接口。
  (4)具体装饰(Concrete Decorator)角色:负责给构件对象添加上附加的责任。
以下示例中,ThirdParty.Java假定是一个现有的或者第三方的功能,因某种原因我们不能直接修改,它提供了一个sayMsg()的方法,而我们现在要做的是想在它的sayMsg()方法中增加一些我们想额外输出的内容,于是我们重写了一个Decorator.java类。MailTest.java是客户端测试程序。
 
IthirdParty.Java--抽象接口类
package decorator.saystr;
public interface IthirdParty {
public String sayMsg();
}
ThirdParty.Java--具体类
===================
public class ThirdParty implements IthirdParty {
public String sayMsg() {
  return "hello";
  }
}

 

Decorator1.java 具体装饰类1
package decorator.saystr;
public class Decorator1 implements IThirdParty {
private IThirdParty thirdParty;
public Decorator1(IThirdParty thirdParty){
this.thirdParty= thirdParty;
}
public String sayMsg(){
return "##1"+ thirdParty.sayMsg() + "##1";
}
}

 

Decorator2.java 具体装饰类2

package decorator.saystr;
public class Decorator2 implements IThirdParty {
private IThirdParty thirdParty;
public Decorator2(IThirdParty thirdParty){
this.thirdParty= thirdParty;
}
public String sayMsg(){
return "##2"+ thirdParty.sayMsg() + "##2";
}
}

 

测试类:

package decorator.saystr;
public class MailTest {
public static void main(String[] args){

  IthirdParty thirdPartyOne =new ThirdParty();
  IthirdParty decorator1 =new Decorator1(thirdPartyOne);
  IthirdParty decorator2 =new Decorator2(decorator1);

  System.out.println(decorator2.sayMsg());
}
}

 

 

执行结果:

  ##2##1hello##1##2

 

装饰模式是利用SetComponent来对对象进行包装的,这样每个装饰对象的实现就和如何使用这个对象分离了,每个装饰对象只关心自己的功能,不用关心如何被添加到对象链当中。
如果只有一个ConcreteComponent类而没有抽象的Component类,那么Decorator类可以是ConcreteComponent的一个子类,同样道理,如果只有一个ConcreteDecorator类那么就没有必要简历一个单独的Decorator类,而可以把Decorator和ConcreteDecorator的责任合并成一个类。
装饰模式是为已有功能动态的添加更多功能的一种方式。
应用场景:当系统需要新功能的时候,是想旧的类中添加新的代码。这些新加的代码通常装饰了原来类的核心职责或主要行为,比如用西装或者嘻哈服来修饰小菜,但这种做法的问题在于,他们在主类中加入了新的字段,新的方法和新的逻辑,从而增加了朱磊的复杂度,就像你起初的那个“人”类,而这些新加入的东西仅仅是为了满足一些只是在某种特殊情况下才会执行的特殊行为的需要。而装饰模式却提供了一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择地、按顺序地使用装饰功能包装对象了。
优点:把类中的装饰功能从类中搬移去除,这样子可以简化原来的类,更大的好处是有效地把类核心职责和装饰功能区别开了,而且可以去除相关类中重复的装饰逻辑。

 

 
 

posted on 2015-07-04 15:41  WhyWin  阅读(1774)  评论(0编辑  收藏  举报

导航