设计模式-装饰模式,介绍装饰模式,及代码实现。
简介 装饰模式是结构型设计模式,动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。
角色
组件抽象类:组件的抽象类,描述简单职责
组件实现类:抽象类的实现类,即被修饰的对象
组件装饰类:装饰类继承组件抽象父类,装饰子类继承装饰父类,不同装饰子类在前一个修饰的基础上继续完成修饰。
实现说明 以人搭配穿衣服为例:人为组件抽象类Component,小明为组件实现类ConcreteComponent,服饰为组件装饰类Decorator,具体的服饰类型为装饰子类,装饰模式是为已有功能动态的添加功能的一种方式。
当系统需要新功能的时候,是像旧的类里面添加新的代码,这些新的代码通常装饰了原有类的核心职责或主要行为,比如穿西装或者嘻哈装,在主类服饰中增加了新的字段,新的方法和新的逻辑,从而增加了主类的复杂度。
代码实现 组件抽象类 1 2 3 4 5 6 7 8 9 10 11 12 public abstract class Component { public abstract void operation () ; }
组件实现类 1 2 3 4 5 6 7 8 9 10 11 12 13 public class ConcreteComponent extends Component { @Override public void operation () { System.out.println("具体对象的操作" ); } }
装饰类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 public abstract class Decorator extends Component { protected Component component; public Component getComponent () { return component; } public void setComponent (Component component) { this .component = component; } @Override public void operation () { if (component != null ) { component.operation(); } } } class ConcreteDecoratorA extends Decorator { private String addedState; @Override public void operation () { super .operation(); addedState = "A中的new state " ; System.out.println(addedState + "具体装饰对象A的操作" ); } } class ConcreteDecoratorB extends Decorator { @Override public void operation () { super .operation(); addedBehavior(); System.out.println("具体装饰对象B的操作" ); } public void addedBehavior () { System.out.print("B中的新增行为 " ); } } class ConcreteDecoratorC extends Decorator { @Override public void operation () { super .operation(); System.out.println("C没有特殊行为 " + "具体装饰对象C的操作" ); } }
客户端调用类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class DecoratorClient { public static void main (String[] args) { ConcreteComponent concreteComponent = new ConcreteComponent(); ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(); ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(); ConcreteDecoratorC concreteDecoratorC = new ConcreteDecoratorC(); concreteDecoratorA.setComponent(concreteComponent); concreteDecoratorB.setComponent(concreteDecoratorA); concreteDecoratorC.setComponent(concreteDecoratorB); concreteDecoratorC.operation(); } }
输出结果:
1 2 3 4 具体对象的操作 A中的new state 具体装饰对象A的操作 B中的新增行为 具体装饰对象B的操作 C没有特殊行为 具体装饰对象C的操作