【设计模式-装饰模式】

来源:互联网 发布:付辛博和井柏然 知乎 编辑:程序博客网 时间:2024/06/10 05:24
在装饰模式中的各个角色有:
  (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
0 0
原创粉丝点击