Java设计模式笔记之组合模式
来源:互联网 发布:网络电视台客户端 编辑:程序博客网 时间:2024/06/05 11:55
1.前言
整体与部分可以被一致对待的问题。组合模式也叫整体与部分模式,是结构性设计模式之一,组合模式比较简单。它将一组相似的对象看作一个对象处理,并根据一个树状结构来组合对象,然后提供一个统一的方法去访问相应的对象,以此忽略掉对象与对象集合之间的差别。
2.定义
组合模式:将对象组合成树形结构以表示‘部分-整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
3.UML图
4.应用场景
表示对象的部分-整体层次结构时;从一个整体中能够独立出部分模块或功能的场景。
5.通用模式代码
//抽象根节点public abstract class Component { //节点名 protected String name; public Component(String name){ this.name = name; } /** * 具体的逻辑方法由子类去实现 */ public abstract void doSomething();}//具体枝干节点public class Composite extends Component { //存储节点的容器 private List<Component> componentList = new ArrayList<>(); /** * * @param name */ public Composite(String name) { super(name); } @Override public void doSomething() { Log.d("zsf", "name:" + name); if (null != componentList){ for(Component c :componentList){ c.doSomething(); } } } /** * 添加子节点 * @param child 子节点 */ public void addChild(Component child){ componentList.add(child); } /** * 移除子节点 * @param child 子节点 */ public void removeChild(Component child){ componentList.remove(child); } /** * 获取子节点 * @param index 子节点对应的下标 * @return 子节点 */ public Component getChildren(int index){ return componentList.get(index); }}
//具体叶子节点public class Leaf extends Component { public Leaf(String name) { super(name); } @Override public void doSomething() { Log.d("zsf","name:" + name); } }
public class ClientActivity extends Activity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //activity_component_client没有其他东西 setContentView(R.layout.activity_component_client); //构造一个根节点 Composite root = new Composite("root"); //构造两个枝干节点 Composite branch1 = new Composite("branch1"); Composite branch2 = new Composite("branch2"); //构造两个叶子节点 Leaf leaf1 = new Leaf("leaf1"); Leaf leaf2 = new Leaf("leaf2"); //将叶子节点添加到枝干节点中 branch1.addChild(leaf1); branch2.addChild(leaf2); //将枝干节点添加到根节点中 root.addChild(branch1); root.addChild(branch2); //执行方法 root.doSomething(); }}
将Composite中的方法同样定义到了Component中去。将组合所使用的方法定义在抽象类的方式称为透明的组合模式。上一个组合模式叫安全的组合模式。透明组合模式的UML图如下:
阅读全文
0 0
- Java设计模式笔记之组合模式
- java设计模式之组合设计模式
- 设计模式学习笔记之组合模式
- 设计模式笔记之---组合模式
- 设计模式学习笔记之组合模式
- 大话设计模式笔记之组合模式
- 设计模式之禅笔记-组合模式
- java设计模式之组合模式
- java设计模式之组合模式Composite
- JAVA设计模式之组合模式
- java设计模式之组合模式
- 设计模式之组合模式java实现
- java设计模式之组合模式
- 【Java设计模式】之组合模式
- Java设计模式之组合模式
- Java设计模式泛型化之组合模式
- java设计模式之组合模式
- JAVA设计模式初探之组合模式
- window.getComputedStyle()方法的使用
- python super()和classmethod
- xml文件读取到数据库
- R语言连接数据库汉字乱码问题
- Spring Cloud Netflix之Eureka Doc Translation
- Java设计模式笔记之组合模式
- CF-Codeforces Round #418 (Div. 2)-C-An impassioned circulation of affection
- 读SDWebImage库系列(1)-如何保证同一时间请求相同URL时,只进行一次网络请求
- Unity Shader入门精要笔记(一):渲染流水线
- [leetcode]: 617. Merge Two Binary Trees
- jackson反序列化时忽略不需要的字段
- 数组操作--增、删、改、查
- IO流
- 51Nod--1019 逆序数