装饰器模式
下面是一个简单的Java代码示例,展示了装饰器模式的实现
// 抽象组件接口
interface Component {
void operation();
}
// 具体组件类
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
// 抽象装饰器类
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰器类A
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addBehavior();
}
private void addBehavior() {
System.out.println("ConcreteDecoratorA add behavior");
}
}
// 具体装饰器类B
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addBehavior();
}
private void addBehavior() {
System.out.println("ConcreteDecoratorB add behavior");
}
}
// 客户端代码
public class DecoratorPatternExample {
public static void main(String[] args) {
// 创建具体组件对象
Component component = new ConcreteComponent();
// 创建具体装饰器对象,并传入具体组件对象
Decorator decoratorA = new ConcreteDecoratorA(component);
Decorator decoratorB = new ConcreteDecoratorB(decoratorA);
// 调用装饰器对象的方法
decoratorB.operation();
}
}
标签:component,void,Component,operation,public,Decorator,10.16
From: https://www.cnblogs.com/luoqingci/p/18556260