设计模式之装饰模式
装饰模式:动态地给一个对象添加一些额外的职责(功能),就增加功能来说,装饰模式比生成子类更为灵活。
装饰模式中有四个角色,抽象构件,具体构件,装饰角色和具体装饰角色。他们之间的UML结构图如下
抽象构件:给出一个接口,规范接收附加责任的对象
具体构件:定义具体类,将来接收附加责任的对象
装饰角色:持有一个构件对象实例,同时定义一个与抽象构件接口一致的接口
具体装饰角色:为构件对象增加附加责任
举个粟子:
<span style="font-size:14px;">package cn.com.taiji.test;
public class DecoratorTest {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA a = new ConcreteDecoratorA();
ConcreteDecoratorB b = new ConcreteDecoratorB();
// 基本组件,进行装饰
a.setComponent(c);
a.operation();// 输出
// 基本的!
// ConcreteDecoratorA
System.out.println("===========");
// 再次进行装饰
b.setComponent(a);
b.operation();// 输出
// 基本的!
// ConcreteDecoratorA
// ConcreteDecoratorB
}
}
// 抽象组件
interface Component {
// 定义标准方法,以规范子类
public void operation();
}
// 一个基本的实现
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("基本的!");
}
}
// 装饰抽象类
abstract class Decorator implements Component {
// 持有抽象组件引用
protected Component component;
// 做了基本的实现
@Override
public void operation() {
if (null != component) {
component.operation();
}
}
public void setComponent(Component component) {
this.component = component;
}
}
// 一个装饰类
class ConcreteDecoratorA extends Decorator {
@Override
public void operation() {
component.operation();
// 进行装饰
System.out.println("ConcreteDecoratorA");
}
}
// 另一个装饰类
class ConcreteDecoratorB extends Decorator {
@Override
public void operation() {
component.operation();
System.out.println("ConcreteDecoratorB");
}
}</span>
装饰模式为已有的功能动态地添加更多的功能的一种方式。
它会保持原来的功能,再增加新的功能,当需要时,客户端可以在运行时根据需要有选择地,按顺序地使用装饰功能包装对象。
这样可以对功能增加,而不用修改功能性代码。
有效地把类的核心职责和装饰功能区分开,而且可以去除相关类中重复的装饰逻辑。