一、基本概念
1、装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。
2、装饰对象包含一个真实对象的引用,非常关键。
3、角色:
A:抽象构件角色(Component):定义一个对象接口或抽象类,可以给这些对象动态地添加职责。
B:具体构件角色(ConcreteComponent):实际被动态地添加职责的对象。
C:抽象装饰者角色(Decorator):实现了Component接口,用来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。
D:具体装饰者角色(ConcreteDecorator):动态地添加职责的对象。
E:客户端(Client)
二、例子(为简单实现,把C省略了)
A:抽象构件角色(Component):
1 package comm.pattern.struct.decorator; 2 3 /** 4 * 5 * @Title: Component.java 6 * @Package: comm.pattern.struct.decorator 7 * @Description: 抽象构建,模拟杨过 8 * @author yangzhancheng 9 * @2020年3月16日:上午12:00:38 10 * 11 */ 12 public interface Component { 13 public void operation(); 14 }
B:具体构件角色(ConcreteComponent):
1 package comm.pattern.struct.decorator; 2 3 public class ConcreteComponent implements Component { 4 5 public void operation() { 6 System.out.print("杨过,名过,字改之,是金庸武侠小说《神雕侠侣》的主人公;"); 7 } 8 9 }
C:抽象装饰者角色(Decorator):
省略。
D:具体装饰者角色(ConcreteDecorator):
D-1:
1 package comm.pattern.struct.decorator; 2 3 /** 4 * 5 * @Title: Decorator.java 6 * @Package: comm.pattern.struct.decorator 7 * @Description: 装饰类 8 * @author yangzhancheng 9 * @2020年3月16日:上午12:05:54 10 * 11 */ 12 class DecoratorA implements Component 13 { 14 private Component component; 15 16 public DecoratorA(Component component) 17 { 18 this.component=component; 19 } 20 21 public void operation() 22 { 23 component.operation(); 24 System.out.print("他在活死人墓待过,练过玉女心经;"); 25 } 26 }
D-2:
1 package comm.pattern.struct.decorator; 2 3 /** 4 * 5 * @Title: DecoratorB.java 6 * @Package: comm.pattern.struct.decorator 7 * @Description: 装饰类 8 * @author yangzhancheng 9 * @2020年3月16日:上午12:10:12 10 * 11 */ 12 class DecoratorB implements Component { 13 14 private Component component; 15 16 public DecoratorB(Component component) { 17 this.component = component; 18 } 19 20 public void operation() { 21 component.operation(); 22 System.out.print("他有一只雕兄"); 23 } 24 }
E:客户端(Client)
1 package comm.pattern.struct.decorator; 2 3 /** 4 * 5 * @Title: Client.java 6 * @Package: comm.pattern.action.templateMethod 7 * @Description: 描述该文件做什么 8 * @author yangzhancheng 9 * @2020年3月1日:下午4:47:17 10 * 11 */ 12 public class Client { 13 14 public static void main(String[] args) { 15 16 Component component = new ConcreteComponent(); 17 component.operation(); 18 19 System.out.println("\n---------------------------------"); 20 Component partyComponentDec = new DecoratorA(component); 21 partyComponentDec.operation(); 22 23 System.out.println("\n---------------------------------"); 24 Component allComponent = new DecoratorB(new DecoratorA(new ConcreteComponent())); 25 allComponent.operation(); 26 } 27 28 }
运行输出
杨过,名过,字改之,是金庸武侠小说《神雕侠侣》的主人公; --------------------------------- 杨过,名过,字改之,是金庸武侠小说《神雕侠侣》的主人公;他在活死人墓待过,练过玉女心经; --------------------------------- 杨过,名过,字改之,是金庸武侠小说《神雕侠侣》的主人公;他在活死人墓待过,练过玉女心经;他有一只雕兄
三、总结
IO流的操作就是典型的装饰模式。后续贴出源代码。