装饰者模式

[复制链接]
发表于 2024-12-26 11:52:24 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×

代码详解:【计划模式】Java 计划模式之装饰者模式(Decorator)_java 装饰者模式-CSDN博客


  1. // 抽象构件角色
  2. public interface Component {
  3.     void operation();
  4. }
  5. // 具体构件角色
  6. public class ConcreteComponent implements Component {
  7.     @Override
  8.     public void operation() {
  9.         System.out.println("执行具体构件对象的操作");
  10.     }
  11. }
  12. // 装饰角色
  13. public class Decorator implements Component {
  14.     protected Component component;
  15.     public Decorator(Component component) {
  16.         this.component = component;
  17.     }
  18.     @Override
  19.     public void operation() {
  20.         if (component != null) {
  21.             component.operation();
  22.         }
  23.     }
  24. }
  25. // 具体装饰角色A
  26. public class ConcreteDecoratorA extends Decorator {
  27.     public ConcreteDecoratorA(Component component) {
  28.         super(component);
  29.     }
  30.     @Override
  31.     public void operation() {
  32.         super.operation();
  33.         addedFunctionA();
  34.     }
  35.     public void addedFunctionA() {
  36.         System.out.println("为构件对象添加功能A");
  37.     }
  38. }
  39. // 具体装饰角色B
  40. public class ConcreteDecoratorB extends Decorator {
  41.     public ConcreteDecoratorB(Component component) {
  42.         super(component);
  43.     }
  44.     @Override
  45.     public void operation() {
  46.         super.operation();
  47.         addedFunctionB();
  48.     }
  49.     public void addedFunctionB() {
  50.         System.out.println("为构件对象添加功能B");
  51.     }
  52. }
复制代码
 装者模式的应用:
-mybatis 里的缓存:
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表