矿泉水网站模板,建网站需要服务器吗,专业网站开发多少钱,wordpress页面颜色装饰器模式允许你通过将对象放入包含行为的特殊包装对象中来为原对象动态添加新的行为。以下是一个简单的 Java 示例#xff1a; // 定义接口
interface Component {void operation();
}// 具体组件实现接口
class ConcreteComponent implements Component {public void opera…装饰器模式允许你通过将对象放入包含行为的特殊包装对象中来为原对象动态添加新的行为。以下是一个简单的 Java 示例 // 定义接口
interface Component {void operation();
}// 具体组件实现接口
class ConcreteComponent implements Component {public void operation() {System.out.println(ConcreteComponent: operation());}
}// 装饰器类实现接口并持有一个 Component 对象
abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component component;}public void operation() {component.operation();}
}// 具体装饰器类扩展 Decorator 类
class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}public void operation() {super.operation();System.out.println(ConcreteDecoratorA: additional operation());}
}// 另一个具体装饰器类
class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component component) {super(component);}public void operation() {super.operation();System.out.println(ConcreteDecoratorB: additional operation());}
}// 示例
public class Main {public static void main(String[] args) {// 创建具体组件Component component new ConcreteComponent();// 使用装饰器包装组件并连续添加装饰器Component decoratedComponent new ConcreteDecoratorA(new ConcreteDecoratorB(component));// 调用操作decoratedComponent.operation();}
} 在这个例子中Component 接口定义了操作方法 operation()ConcreteComponent 是具体组件实现了该接口。Decorator 是装饰器抽象类持有一个 Component 对象并实现了 operation() 方法来委托给被装饰的组件。ConcreteDecoratorA 和 ConcreteDecoratorB 是具体装饰器类它们扩展了 Decorator 并添加了额外的操作。 在 Main 类中我们首先创建了一个具体组件 ConcreteComponent然后通过创建装饰器链将其包装最后调用操作方法。由于装饰器链的存在实际执行时会先执行 ConcreteDecoratorB 的操作然后再执行 ConcreteDecoratorA 的操作最后执行具体组件的操作。