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

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

转载于:https://www.cnblogs.com/davidshi/p/3362807.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值