概念
装饰器模式(Decorator Pattern)允许向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于结构型模式,它是作为现有的类的一个包装。
这种模式创建了一个装饰类,用来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
优点
装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
缺点
多层装饰比较复杂
使用场景
- 扩展一个类的功能。
- 动态增加功能,动态撤销。
类图
Component:组件对象的接口,可以给这些对象动态的添加职责;
ConcreteComponent:具体的组件对象,实现了组件接口。该对象通常就是被装饰器装饰的原始对象,可以给这个对象添加职责;
Decorator:所有装饰器的父类,需要定义一个与组件接口一致的接口(主要是为了实现装饰器功能的复用,即具体的装饰器A可以装饰另外一个具体的装饰器B,因为装饰器类也是一个Component),并持有一个Component对象,该对象其实就是被装饰的对象。如果不继承组件接口类,则只能为某个组件添加单一的功能,即装饰器对象不能在装饰其他的装饰器对象。
ConcreteDecorator:具体的装饰器类,实现具体要向被装饰对象添加的功能。用来装饰具体的组件对象或者另外一个具体的装饰器对象。
代码
Component.java
package com.cnpc.study;
public interface Component {
void operation();
}
ConcreateComponet.java
package com.cnpc.study;
public class ConcreateComponent implements Component {
public void operation() {
System.out.println("i am ConcreateComponent");
}
}
Decorator.java
package com.cnpc.study;
public abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
System.out.println("I am Decorator");
}
}
DecoratorA.java
package com.cnpc.study;
public class DecoratorA extends Decorator {
public DecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
component.operation();
System.out.println("i am Decorator A");
}
}
DecoratorB.java
package com.cnpc.study;
public class DecoratorB extends Decorator {
public DecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
component.operation();
System.out.println("i am Decorator B");
}
}
DecoratorC.java
package com.cnpc.study;
public class DecoratorC extends Decorator {
public DecoratorC(Component component) {
super(component);
}
@Override
public void operation() {
component.operation();
System.out.println("i am Decorator C");
}
}
测试入口Main.java
package com.cnpc.study;
public class Main {
public static void main(String[] args) {
Component a1 = new ConcreateComponent();
Decorator d = new DecoratorA(new DecoratorB(new DecoratorC(a1)));
d.operation();
}
}