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

设计模式的定义

1 组合模式:

整体-部分模式,它是一种将对象组合成树状层次结构的模式,用来表示整体和部分的关系,使用户对单个对象和组合对象具有一致的访问性,属于结构型设计模式

1.1 特点:

  1. 组合模式使得客户端代码可以一致的处理单个对象和组合对象
  2. 更容易在组合体内加入新的对象,客户端不会因为加入新的对象而改变原代码,满足''开闭原则''

1.2 缺点:

  1. 设计较复杂,客户端需要花更多的时间理清类之间的关系
  2. 不容易限制容器中的构建
  3. 不容易用继承的方法来增加构件的新功能 

1.3 结构:

  1. 抽象构件角色:
  2. 树叶构件角色:
  3. 树枝构件角色/中间构件: 

1.4 组合模式分为透明式的组合模式和安全式的组合模式。 

  1. 透明式:抽象构件声明了所有子类中的全部方法,客户端无需区别树叶对象和树枝对象
  2. 安全式:将管理子构件的方法移到树枝构件中,抽象构件和树叶构件没有对子对象的管理方法

1.5 代码实现

透明模式

public class CompositePattern {public static void main(String[] args) {Component c0 = new Composite();Component c1 = new Composite();Component leaf1 = new Leaf("1");Component leaf2 = new Leaf("2");Component leaf3 = new Leaf("3");c0.add(leaf1);c0.add(c1);c1.add(leaf2);c1.add(leaf3);c0.operation();}
}
//抽象构件
interface Component {public void add(Component c);public void remove(Component c);public Component getChild(int i);public void operation();
}
//树叶构件
class Leaf implements Component {private String name;public Leaf(String name) {this.name = name;}public void add(Component c) {}public void remove(Component c) {}public Component getChild(int i) {return null;}public void operation() {System.out.println("树叶" + name + ":被访问!");}
}
//树枝构件
class Composite implements Component {private ArrayList<Component> children = new ArrayList<Component>();public void add(Component c) {children.add(c);}public void remove(Component c) {children.remove(c);}public Component getChild(int i) {return children.get(i);}public void operation() {for (Object obj : children) {((Component) obj).operation();}}
}
树叶1:被访问!
树叶2:被访问!
树叶3:被访问!

安全模式

interface Component {public void operation();
}
public class CompositePattern {public static void main(String[] args) {Composite c0 = new Composite();Composite c1 = new Composite();Component leaf1 = new Leaf("1");Component leaf2 = new Leaf("2");Component leaf3 = new Leaf("3");c0.add(leaf1);c0.add(c1);c1.add(leaf2);c1.add(leaf3);c0.operation();}
}

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

相关文章:

  • 【Kubernetes】存储类StorageClass
  • 【LLM】大模型之RLHF和替代方法(DPO、RAILF、ReST等)
  • Spring Boot监听redis过期的key
  • day01、什么是数据库系统?
  • 2023年医疗器械行业分析(京东医疗器械运营数据分析):10月销额增长53%
  • MISRA C++ 2008 标准解析
  • Linux16 ftp文件服务区、vsftpd文件系统服务安装、lftp客户端安装、NFS远程共享存储
  • [排序篇] 冒泡排序
  • CGAL的四面体网格重构
  • 排序-选择排序与堆排序
  • d2l绘图不显示的问题
  • 智能优化算法应用:基于人工蜂群算法3D无线传感器网络(WSN)覆盖优化 - 附代码
  • 云原生的 CI/CD 框架tekton - Trigger(二)
  • maven环境搭建
  • 利用Rclone将阿里云对象存储迁移至雨云对象存储的教程,对象存储数据迁移教程
  • 二叉树的前序遍历
  • final的安全发布
  • 3易懂AI深度学习算法:长短期记忆网络(Long Short-Term Memory, LSTM)生成对抗网络 优化算法进化算法
  • 云计算 云原生
  • 深拷贝、浅拷贝 react的“不可变值”
  • 赛宁网安多领域亮相第三届网络空间内生安全发展大会
  • LintCode 123 · Word Search (DFS字符处理经典题!)
  • SpringCloud面试题——Sentinel
  • 【精选】 VulnHub (超详细解题过程)
  • 数据结构与算法-Rust 版读书笔记-2线性数据结构-队列
  • Android Kotlin Viewbinding封装
  • Flutter:web项目跨域问题解决
  • 汽车标定技术(十二)--A2L文件生成的方法
  • 《PySpark大数据分析实战》-03.了解Hive
  • 经验分享|MySQL分区实战(RANGE)