当前位置: 首页 > news >正文

设计模式-结构模式-装饰模式

装饰模式(Decorator Pattern):动态地给一个对象增加一些额外的职责,就增加对象功能来说,装饰模式比生成子类实现更为灵活。装饰模式是一种对象结构型模式。

 

//首先,定义一个组件接口:
public interface Component {void operation();
}
//然后,创建一个实现了该接口的具体组件类
public class ConcreteComponent implements Component {@Overridepublic void operation() {System.out.println("ConcreteComponent operation");}
}
//接下来,创建一个抽象装饰器类,它实现了相同的接口并持有一个组件对象的引用:
public abstract class Decorator implements Component {protected Component component;public Decorator(Component component) {this.component = component;}@Overridepublic void operation() {component.operation();}
}
//最后,创建具体装饰器类,继承自抽象装饰器并添加额外功能:
public class ConcreteDecoratorA extends Decorator {public ConcreteDecoratorA(Component component) {super(component);}@Overridepublic void operation() {super.operation();addedFunctionalityA();}public void addedFunctionalityA() {System.out.println("Added functionality A");}
}public class ConcreteDecoratorB extends Decorator {public ConcreteDecoratorB(Component component) {super(component);}@Overridepublic void operation() {super.operation();addedFunctionalityB();}public void addedFunctionalityB() {System.out.println("Added functionality B");}
}
现在,你可以创建客户端代码来展示如何使用装饰器:
public class DecoratorPatternExample {public static void main(String[] args) {Component component = new ConcreteComponent();System.out.println("Operation of ConcreteComponent:");component.operation();System.out.println("\nDecorating with ConcreteDecoratorA:");component = new ConcreteDecoratorA(component);component.operation();System.out.println("\nDecorating with ConcreteDecoratorB:");component = new ConcreteDecoratorB(component);component.operation();}
}

http://www.lryc.cn/news/309314.html

相关文章:

  • MySQL:一行记录如何
  • ‘grafana.ini‘ is read only ‘defaults.ini‘ is read only
  • 博途PLC 面向对象系列之“输送带控制功能块“(SCL代码)
  • 2024-02学习笔记
  • 最新消息:英特尔宣布成立全新独立运营的FPGA公司——Altera
  • RC正弦波振荡电路
  • 【Git学习笔记】提交PR
  • 线程池的相关参数
  • 图书推荐||Word文稿之美
  • 前端导出word文件的多种方式、前端导出excel文件
  • Linux和Windows操作系统在腾讯云幻兽帕鲁服务器上的内存占用情况如何?
  • 腾讯云4核8G的云服务器性能水平?使用场景说明
  • 1_SQL
  • PoC免写攻略
  • c1-周考2
  • express+mysql+vue,从零搭建一个商城管理系统7--文件上传,大文件分片上传
  • markdown的使用(Typora)
  • 【python】json转成成yaml中文编码异常显示成:\u5317\u4EAC\u8DEF123\u53F7
  • Python 实现Excel自动化办公(中)
  • MCTS代码
  • Java 中notify 和 notifyAll 方法介绍
  • Leetcode :杨辉三角
  • MWC 2024丨美格智能CEO杜国彬出席中国联通创新成果发布会并发表主题演讲
  • 个人建站前端篇(七)vite + vue3企业级项目模板
  • centos7 安装 docker-compose
  • 剑指offer面试题28:对称的二叉树
  • JS:原型与原型链(附带图解与代码)
  • 电子电器架构新趋势 —— 最佳着力点:域控制器
  • C++记录
  • ConcurrentModificationException并发修改异常