介绍
动态地给一个对象添加一些额外的职责。就增加功能来说,D e c o r a t o r 模式相比生成子类更为灵活
实现
ConcreteComponent类是被装饰类,Decorator是装饰类,代码如下:
Component 类
package com.decorator;
public interface Component {
void operation();
}
ConcreteComponent 类
package com.decorator;
public class ConcreteComponent implements Component{
@Override
public void operation() {
System.out.println("this is the original operation");
}
}
Decorator 类
package com.decorator;
public class Decorator implements Component {
private Component component;
public Decorator(Component component)
{
this.component = component;
}
@Override
public void operation() {
System.out.println("before decorator");
component.operation();
System.out.println("after decorator");
}
}
DecoratorTest 类
package com.decorator;
public class DecoratorTest {
public static void main(String []args)
{
Component component = new ConcreteComponent();
Decorator decorator = new Decorator(component);
decorator.operation();
}
}
运行结果
before decorator
this is the original operation
after decorator