装饰者与适配者模式的区别

1.关于新职责:适配器也可以在转换时增加新的职责,但主要目的不在此。装饰者模式主要是给被装饰者增加新职责的。
2.关于原接口:适配器模式是用新接口来调用原接口,原接口对新系统是不可见或者说不可用的。装饰者模式原封不动的使用原接口,系统对装饰的对象也通过原接口来完成使用。(增加新接口的装饰者模式可以认为是其变种--“半透明”装饰者)
3.关于其包裹的对象:适配器是知道被适配者的详细情况的(就是那个类或那个接口)。装饰者只知道其接口是什么,至于其具体类型(是基类还是其他派生类)只有在运行期间才知道。[1]

4代码示例

在装饰模式中的各个角色有:
  (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";
}
}
Decorator1.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";
}
}
MailTest.java
====================
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
posted @ 2013-10-11 10:22  红宝石  阅读(572)  评论(0编辑  收藏  举报