目录
一、类图
二、模式定义
装饰模式(Decorator Pattern):
动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。
装饰模式是一种对象结构型模式。
三、模式角色说明
Component(抽象构件):
它是具体构件和抽象装饰类的共同父类,声明了在具体构件中实现的业务方法
它的引入可以使客户端以一致的方式处理未被装饰的对象以及装饰之后的对象,实现客户端的透明操作。
ConcreteComponent(具体构件):
它是抽象构件类的子类,实现了在抽象构件中声明的方法
用于定义具体的构件对象
装饰器可以给它增加额外的职责(方法)
Decorator(抽象装饰类):
它也是抽象构件类的子类
用于给具体构件增加职责,但是具体职责在其子类中实现。
它维护一个指向抽象构件对象的引用,通过该引用可以调用装饰之前构件对象的方法
通过其子类扩展该方法,以达到装饰的目的。
ConcreteDecorator(具体装饰类):
它是抽象装饰类的子类,负责向构件添加新的职责。
每一个具体装饰类都定义了一些新的行为,它可以调用在抽象装饰类中定义的方法,并可以增加新的方法用以扩充对象的行为。
四、代码示例
Component(抽象构件):
package com.yan.pattern.decorator;
public interface Component {
public void operator();
}
ConcreteComponent(具体构件):
package com.yan.pattern.decorator;
public class ConcreteComponent implements Component{
public void operator() {
System.out.println("我是需要装饰的对象");
}
}
Decorator(抽象装饰类):
package com.yan.pattern.decorator;
public abstract class Decorator implements Component{
Component component;
public Decorator(Component component) {
this.component = component;
}
public void operator() {
component.operator();
}
}
ConcreteDecorator(具体装饰类):
package com.yan.pattern.decorator;
public class ConcreteDecoratorA extends Decorator{
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operator() {
super.operator();
addDecorator();
}
private void addDecorator() {
System.out.println("我是A装饰者,这是我要装饰的方法");
}
}
package com.yan.pattern.decorator;
public class ConcreteDecoratorB extends Decorator{
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operator() {
super.operator();
addDecorator();
}
private void addDecorator() {
System.out.println("我是B装饰者,这是我要装饰的方法");
}
}
Client(客户端测试)
package com.yan.pattern.decorator;
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
component = new ConcreteDecoratorA(component);
component.operator();
System.out.println("-----------------------------");
component = new ConcreteDecoratorB(component);
component.operator();
}
}
测试结果
我是需要装饰的对象
我是A装饰者,这是我要装饰的方法
-----------------------------
我是需要装饰的对象
我是A装饰者,这是我要装饰的方法
我是B装饰者,这是我要装饰的方法