装饰模式:动态地给一个对象增加一些额外的职责,就增加功能来说,装饰模式比生成子类更灵活。
白话:以人穿衣服鞋子为例,衣服鞋子这些类不是人的属性,但要实现人各种不同的搭配;如果将衣服鞋子的属性放到人这个类,则会使人这个类无比臃肿,此时可以使用装饰的方式:鞋子和衣服类提供装饰方法。当人要装配上衣服时,将人传递给衣服类,让衣服给人装饰上,鞋子亦同。
模式简化:
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