装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
特点
(1) 装饰对象和真实对象有相同的接口。这样客户端对象就能以和真实对象相同的方式和装饰对象交互。
(2) 装饰对象包含一个真实对象的引用(reference)
(3) 装饰对象接受所有来自客户端的请求。它把这些请求转发给真实的对象。
(4) 装饰对象可以在转发这些请求以前或以后增加一些附加功能。这样就确保了在运行时,不用修改给定对象的结构就可以在外部增加附加的功能。在面向对象的设计中,通常是通过继承来实现对给定类的功能扩展。
适用性
以下情况使用Decorator模式
1. 需要扩展一个类的功能,或给一个类添加附加职责。
2. 需要动态的给一个对象添加功能,这些功能可以再动态的撤销。
3. 需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变的不现实。
4. 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。
优点
1. Decorator模式与继承关系的目的都是要扩展对象的功能,但是Decorator可以提供比继承更多的灵活性。
2. 通过使用不同的具体装饰类以及这些装饰类的排列组合,设计师可以创造出很多不同行为的组合。
缺点
1. 这种比继承更加灵活机动的特性,也同时意味着更加多的复杂性。
2. 装饰模式会导致设计中出现许多小类,如果过度使用,会使程序变得很复杂。
3. 装饰模式是针对抽象组件(Component)类型编程。但是,如果你要针对具体组件编程时,就应该重新思考你的应用架构,以及装饰者是否合适。当然也可以改变Component接口,增加新的公开的行为,实现“半透明”的装饰者模式。在实际项目中要做出最佳选择。
第一版UML类图
第二版UML类图
抽象了子类中 Parent 类型的公共成员变量
第三版UML类图
将Parent 类接口化,子类依赖于接口,新增了Parent接口的一个具体类用以创建子类实例
装饰模式使得下层类可以复用其依赖的上层类的所有扩展功能。
Parent 接口类
package com.lx.decorator;
public interface Component {
public void option();
}
Parent 接口具体类
package com.lx.decorator;
public class ConcreteComponent implements Component{
protected String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ConcreteComponent() {
}
public void option() {
System.out.println(name+"出现了");
}
}
抽象类 PublicPart
package com.lx.decorator;
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component =component;
// TODO Auto-generated constructor stub
}
}
子类一
package com.lx.decorator;
public class Tshirts extends Decorator{
public Tshirts(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
public void option() {
//先调用 component的option方法
if(component != null){
component.option();
}
System.out.println("TShirt华丽丽登场");
}
}
子类二
package com.lx.decorator;
public class Shoots extends Decorator{
public Shoots(Component component) {
super(component);
// TODO Auto-generated constructor stub
}
public void option() {
//先调用 component的option方法
if(component != null){
component.option();
}
System.out.println("Shoot华丽丽登场");
}
}
测试类
package com.lx.decorator;
import org.junit.Test;
public class TestDecorator {
@Test
public void TestDc(){
ConcreteComponent cc =new ConcreteComponent();
cc.setName("小明");
Tshirts ts = new Tshirts(cc);
Shoots st= new Shoots(ts);
Shoots sss= new Shoots(st);
sss.option();
}
}
测试结果
小明出现了
TShirt华丽丽登场
Shoot华丽丽登场
Shoot华丽丽登场