日拱一卒(二十六)

装饰模式:动态地给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活。

         白话:以人穿衣服鞋子为例,衣服鞋子这些类不是人的属性,但要实现人各种不同的搭配;如果将衣服鞋子的属性放到人这个类,则会使人这个类无比臃肿,此时可以使用装饰的方式:鞋子和衣服类提供装饰方法。当人要装配上衣服时,将人传递给衣服类,让衣服给人装饰上,鞋子亦同。

模式简化:

1. 如果只有一个Concrete Component类而没有抽象的Component接口时,可以让Decorator继承Concrete Component。

2. 如果只有一个Concrete Decorator类时,可以将Decorator和Concrete Decorator合并。

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

















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值