装饰模式(Decorator pattern): 又名包装模式(Wrapper pattern), 它以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。java
装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任。换言之,客户端并不会以为对象在装饰前和装饰后有什么不一样。app
装饰模式能够在不创造更多子类的状况下,将对象的功能加以扩展。ide
装饰模式 把客户端的调用委派到被装饰类。装饰模式的关键在于这种扩展彻底是透明的。测试
组成:this
1.抽象构件角色(Component):给出一个抽象类或接口,以规范准备接收附加责任的对象。spa
2.具体构件角色(Concrete Component):定义一个将要接收附加责任的类。设计
3.装饰角色(Decorator):持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口3d
4.具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。代理
特色:code
代码实例:
抽象的构建角色:
1 public interface Componment //抽象的构件角色,给出一个抽象接口,规范准备接收附加责任的对象 2 { 3 public void doSomething(); 4 }
具体的构建角色:
1 public class ConcreteComponment implements Componment//具体构建角色,定义一个要接收附加责任的类 2 { 3 public void doSomething() 4 { 5 System.out.println("功能A"); 6 7 } 8 }
装饰角色:
1 public class Decorator implements Componment //装饰角色, 2 { 3 private Componment componment; //持有一个构件(Componment)对象的引用 4 5 public Decorator(Componment componment) 6 { 7 this.componment = componment; 8 } 9 public void doSomething() 10 { 11 componment.doSomething(); 12 } 13 }
具体装饰角色1:
1 public class ConcreteDecorator1 extends Decorator //具体装饰角色1 2 { 3 4 public ConcreteDecorator1(Componment componment) 5 { 6 super(componment); 7 } 8 9 public void doSomething() 10 { 11 super.doSomething(); 12 this.doAnotherthing(); 13 } 14 15 private void doAnotherthing() 16 { 17 System.out.println("功能B"); 18 } 19 20 }
具体装饰角色2:
1 public class ConcreteDecorator2 extends Decorator 2 { 3 public ConcreteDecorator2(Componment componment) 4 { 5 super(componment); 6 } 7 8 @Override 9 public void doSomething() 10 { 11 super.doSomething(); 12 this.doAnotherthing(); 13 } 14 15 private void doAnotherthing() 16 { 17 System.out.println("功能C"); 18 } 19 20 }
测试:
1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 Componment componment = new ConcreteComponment(); 6 7 Componment componment2 = new ConcreteDecorator1(componment); 8 9 Componment componment3 = new ConcreteDecorator2(componment2); 10 11 componment3.doSomething(); //功能A 12 13 14 } 15 }
输出结果:
功能A
功能B
功能C
对具体的构建角色进行了“包装”,就实现了更多的功能。到底须要多少包装,咱们能够本身决定,体现了动态性和灵活性。
java I/O采用装饰模式实现。
装饰模式用来扩展特定对象的功能,即动态的给对象添加特定的责任(功能),而继承是静态的分配职责,会致使不少子类的产生,缺少灵活性。