-
Notifications
You must be signed in to change notification settings - Fork 0
装饰模式
ZHI-XINHUA edited this page Jan 11, 2019
·
1 revision
装饰模式又叫包装模式。装饰模式以对客户端透明的方法扩展对象的功能,==是继承关系的一个替代方案==。 通俗的说,装饰模式是动态地给一个对象添加一些额外的职责,就增加功能来说,装饰模式闭生成子类更为灵活。
装饰模式类图:
装饰模式中的角色:
- 抽象构件角色:抽象接口,以规范准备接收附加责任的对象
- 具体构件角色:定义一个将要接收附加责任的类
- 装饰角色:持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口
- 具体装饰角色:负责给构件对象"粘上"附加的责任
1、抽象构件角色(Component): 定义成一个对象接口,可以给这些对象动态添加职责
public interface Component {
//职责
void operation();
}
2、具体构件角色(ConcreteComponent):构件实现类,实现具体的职责
public class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println(" ConcreteComponent --> operation()");
}
}
3、装饰角色(Decorator):定义私有属性Component,引用了构件对象; 并实现构件接口,实际上调用的是具体构件的职责。
public abstract class Decorator implements Component
{
//持有Component对象
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
4、具体装饰角色(ConcreteDecoratorA、ConcreteDecoratorB): 对构件对象进行装饰
public class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
/**
* 私有的装饰
*/
private void addDecoratorA(){
System.out.println("装饰A ConcreteDecoratorA --> addDecoratorA");
}
public void operation() {
//添加装饰
addDecoratorA();
super.operation();
}
}
5、测试:
public static void main(String[] args) {
//原来的对象
ConcreteComponent component = new ConcreteComponent();
component.operation();
//具体装饰A,给职责附加装饰,即给component进行包装
ConcreteDecoratorA concreteDecoratorA = new ConcreteDecoratorA(component);
concreteDecoratorA.operation();
//具体装饰B,给职责附加装饰
ConcreteDecoratorB concreteDecoratorB = new ConcreteDecoratorB(component);
concreteDecoratorB.operation();
}
- 需要扩展一个类的功能,或者给一个类增加附加责任。(比继承灵活)
- 需要动态给一个对象增加功能,这些功能可以动态撤销
- 需要添加由一些基本功能的排列组合而产生大量的功能,从而使继承关系变得不现实。
参考文章:
设计模式