Component
public interface Component {
public void doSomething();
}
ConcreteComponent
public class ConcreteComponent implements Component {
@Override
public void doSomething() {
System.out.println("Function ");
}
}Decorator
public class Decorator implements Component {
private Component component;
public Decorator(Component component){
this.component = component;
}
@Override
public void doSomething() {
this.component.doSomething();
}
}
ConcreteDecorator1
public class ConcreteDecorator1 extends Decorator {
public ConcreteDecorator1(Component component) {
super(component);
}
@Override
public void doSomething(){
super.doSomething();
doAnotherthing();
}
private void doAnotherthing(){
System.out.println("Function 1");
}
}
ConcreteDecorator2
public class ConcreteDecorator2 extends Decorator {
public ConcreteDecorator2(Component component) {
super(component);
}
@Override
public void doSomething(){
super.doSomething();
doAnotherthing();
}
private void doAnotherthing(){
System.out.println("Function 2");
}
}Client
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component component2 = new ConcreteDecorator1(component);
Component component3 = new ConcreteDecorator2(component2);
component3.doSomething();
}
}

本文深入探讨了装饰器模式在组件设计中的应用,通过实例展示了如何使用装饰器来扩展组件的功能,同时保持代码的清晰和可维护性。具体介绍了组件、混凝土组件、装饰器和两个具体装饰器类的实现,最后通过客户端代码演示了如何组合这些组件和装饰器。
2906

被折叠的 条评论
为什么被折叠?



