装饰器模式
-
装饰器模式结构图
-
示例代码:
// 抽象公共类 public abstract class Component { public abstract void work(); } // 具体被装饰对象 public class People extends Component{ @Override public void work() { System.out.println("开始起床去上班......"); } } // 抽象装饰器类 public abstract class WearDecorator extends Component{ protected Component component; public WearDecorator(Component component) { this.component = component; } } // 具体装饰类1 public class ShoeDecorator extends WearDecorator{ public ShoeDecorator(Component component) { super(component); } @Override public void work() { component.work(); System.out.println("穿上运动鞋......"); } } // 具体装饰类2 public class ShirtDecorator extends WearDecorator{ public ShirtDecorator(Component component) { super(component); } @Override public void work() { component.work(); System.out.println("穿上T恤......"); } } // 具体装饰类3 public class PantsDecorator extends WearDecorator{ public PantsDecorator(Component component) { super(component); } @Override public void work() { component.work(); System.out.println("穿上运动裤......"); } } // 具体装饰类4 public class HatDecorator extends WearDecorator{ public HatDecorator(Component component) { super(component); } @Override public void work() { component.work(); System.out.println("戴上网球帽...."); } } // 测试 public class DecoratorTest { public static void main(String[] args) { People people = new People(); ShirtDecorator shirt = new ShirtDecorator(people); PantsDecorator pants = new PantsDecorator(shirt); ShoeDecorator shoes = new ShoeDecorator(pants); HatDecorator hat = new HatDecorator(shoes); hat.work(); } }
-
总结:
优点:可以动态的给一个对象扩展功能,即插即用,可以通过不同的装饰器排列组合,实现不同效果,并且遵循开闭原则;
缺点:会出现更多代码和类,增加了程序的复杂性.