当想要对已有的对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强功能。那么自定义的该类称为装饰类。装饰类通常会通过构造方法接收被装饰的对象。并基于被装饰的对象的功能,提供更强的功能。

(1) 抽象的构建角色( Component):
它是一个接口,封装了将要添加的功能(方法)。
(2) 具体的构建角色( ConcreteComponent ):
它是一个类,该类实现了 Component 接口,因此该类中封装了将要添加的功能的一种实现方法。
(3) 装饰角色(Decorator):
它是一个类,该类也实现了
Component
接口,同时也必须持有接口
Component
的对象的引用,
该类也实现了
Component
接口中的方法。
a:
该类的构造方法需要传递过来一个
Component
对象的引用。
b:
重写的方法(即是添加的功能)需要调用
Component
对象的该方法。
(4)
具体的装饰角色ConcreteDecorator(
Decorator
类的子类,可以有一个,也可以有多个):
这些类继承了类
Decorator,
要重写父类的方法(要添加的功能),和自身的构造方法。
a:
构造方法要用到
super。
b:
第一步:super
父类的该方法。
第二步:添加自己的功能。
装饰设计模式与继承
装饰设计模式 | 继承 | |||||||||
用来扩展特定对象的功能 | 用来扩展一类对象的功能 | |||||||||
不需要子类 | 需要子类 | |||||||||
动态地 | 静态地 | |||||||||
运行时分配职责 | 编译时分派职责 | |||||||||
很容易增加任何的 | 困难 | |||||||||
更多的灵活性 | 缺乏灵活性 | |||||||||
对于一个给定的对象,同时可能有不同的装饰对象,客户端可以通过它的需要选择合适的装饰对象发送消息。 | ||||||||||
防止由于子类而导致的复杂和混乱 导致很多子类产生,在一些场合,暴漏类的层次 |
举例:扩展结婚功能的装饰设计实例
抽象的构建角色( Component)
1 //抽象接口,规范准备接收附加责任的对象 2 public interface Component { 3 public void method(); 4 }
具体的构建角色( ConcreteComponent )
1 /* 2 接收附加责任, 此类型的类可以有多个, 只对应一个Decorator类 3 */ 4 public class ConcreteComponent implements Component { 5 public ConcreteComponent(){} 6 public void method() 7 { 8 System.out.println("结婚"); 9 } 10 }
装饰角色(Decorator)
1 /* 2 装饰角色,持有一个构建(Component)对象的实例,并定义一个与抽象构建接口一致的接口 3 */ 4 public class Decorator implements Component { 5 private Component component; 6 public Decorator(){} 7 public Decorator(Component component) 8 { 9 this.component = component; 10 } 11 12 public void method() { 13 component.method(); 14 } 15 }
具体的装饰角色ConcreteDecorator( Decorator 类的子类,可以有一个,也可以有多个)
1 /* 2 添加附加责任 3 */ 4 public class ConcreteDecorator extends Decorator { 5 6 public ConcreteDecorator(){} 7 8 public ConcreteDecorator(Component component) 9 { 10 super(component); 11 } 12 13 public void method() 14 { 15 this.addedMethod(); 16 super.method(); 17 } 18 19 public void addedMethod() 20 { 21 System.out.println("发喜帖"); 22 System.out.println("摆酒席"); 23 } 24 }
客户端类
1 /* 2 客户端类 3 */ 4 public class Client { 5 public static void main(String[] args) { 6 Component component = new ConcreteComponent(); 7 Decorator decorator = new ConcreteDecorator(component); 8 //客户端不变, 但已增加了责任。确保在运行时,不用修改给定对象结构就可以在外部增加附加的功能。 9 decorator.method(); 10 11 } 12 }
装饰设计模式被大量应用在java的IO体系中,例如
Reader -------相当于Component
丨--InputStreamReader --------相当于ConcreteComponent
丨--BufferedReader -------装饰增强InputStreamReader,特有readLine()功能,相当于Decorator
丨--LineNumberReader --------BufferedReader的子类,在BufferedReader的基础上,增加跟踪行号的功能,相当于ConcreteDecorator