欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Java装饰器模式,装饰器模式通常通过创建一个接口和一个或多个实现了该接口的类来开始,然后创建装饰器类,这些类也实现了相同的接口

Java装饰器模式,装饰器模式通常通过创建一个接口和一个或多个实现了该接口的类来开始,然后创建装饰器类,这些类也实现了相同的接口

2024/10/25 10:23:29 来源:https://blog.csdn.net/qq_42623400/article/details/139495853  浏览:    关键词:Java装饰器模式,装饰器模式通常通过创建一个接口和一个或多个实现了该接口的类来开始,然后创建装饰器类,这些类也实现了相同的接口

1、定义一个接口Component

public interface Component {  void operation();  
}

2、创建一个实现了Component接口的简单类SimpleComponent

public class SimpleComponent implements Component {  @Override  public void operation() {  System.out.println("SimpleComponent operation.");  }  
}

3、创建一个装饰器基类Decorator,它也实现了Component接口,并持有一个对Component对象的引用

public abstract class Decorator implements Component {  protected Component component;  public Decorator(Component component) {  this.component = component;  }  @Override  public void operation() {  if (component != null) {  component.operation();  }  }  
}

4、创建一个具体的装饰器类,例如ConcreteDecoratorA,它添加了一些额外的功能

public class ConcreteDecoratorA extends Decorator {  public ConcreteDecoratorA(Component component) {  super(component);  }  @Override  public void operation() {  super.operation(); // 调用被装饰对象的operation方法  addedFunctionA(); // 添加额外的功能A  }  private void addedFunctionA() {  System.out.println("ConcreteDecoratorA added function.");  }  
}

5、编写一个测试类来展示如何使用装饰器

public class DecoratorPatternDemo {  public static void main(String[] args) {  // 创建一个简单组件  Component simpleComponent = new SimpleComponent();  // 使用装饰器A装饰简单组件  Component decoratedComponent = new ConcreteDecoratorA(simpleComponent);  // 调用被装饰后的组件的operation方法  decoratedComponent.operation();  }  
}

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com