java设计模式之组合设计模式
来源:互联网 发布:淘宝公司在哪里 编辑:程序博客网 时间:2024/05/21 06:23
一,需求
- 现在我们有一棵树,这棵树有树枝,和树叶,树叶是长在树枝上,其中树叶具有光合作用,如果折断一个树枝,那么它可能拥有的分支和树叶都会消失,如果生长出一个树枝,它可能会有若干树枝和树叶。使用代码实现
二,需求分析
- 这是一个典型的部分整体结构模式,是一个递归的结构,可以使用组合模式来实现
三,上代码
public interface Tree { // 添加树枝或者树叶 void addLeaf(Tree tree); // 删除树枝或者树叶 void removeLeaf(Tree tree); // 光合作用--叶子才有的功能 void photosynthetic();}//树枝public class Trunk implements Tree { private List<Tree> trees = new ArrayList<>(); public List<Tree> getTrees() { return trees; } public void setTrees(List<Tree> trees) { this.trees = trees; } @Override public void addLeaf(Tree tree) { trees.add(tree); } @Override public void removeLeaf(Tree tree) { trees.remove(tree); } @Override public void photosynthetic() { listRound(trees); } //递归执行树叶的光合作用,保证每片叶子能光合作用 private void listRound(List<Tree> trees) { if (trees == null || trees.size() ==0){ return ; } for (Tree tree:trees){ if (!(tree instanceof Trunk)){ tree.photosynthetic(); } else { Trunk trunk = (Trunk) tree; listRound(trunk.getTrees()); } } }}// 叶子public class Leaf implements Tree { private String name; public Leaf(String name) { this.name = name; } @Override public void addLeaf(Tree tree) { throw new RuntimeException("leaf cannot add tree"); } @Override public void removeLeaf(Tree tree) { throw new RuntimeException("leaf cannot remove tree"); } @Override public void photosynthetic() { System.out.println(name+" leaf 进行光合作用"); }}// 客户端public class Client { public static void main(String[] args) { Tree trunk1 = new Trunk(); Tree leaf1 = new Leaf("1"); Tree leaf2 = new Leaf("2"); Tree leaf3 = new Leaf("3"); Tree leaf4 = new Leaf("4"); trunk1.addLeaf(leaf1); trunk1.addLeaf(leaf2); trunk1.addLeaf(leaf3); trunk1.addLeaf(leaf4); Tree trunk2 = new Trunk(); Tree leaf5 = new Leaf("5"); Tree leaf6 = new Leaf("6"); Tree leaf7 = new Leaf("7"); Tree leaf8 = new Leaf("8"); trunk2.addLeaf(leaf5); trunk2.addLeaf(leaf6); trunk2.addLeaf(leaf7); trunk2.addLeaf(leaf8); trunk1.addLeaf(trunk2); trunk1.photosynthetic(); }}
四,总结
- 客户端调用了统一的接口,不需要进行了解其中代码的具体实现
- 服务端不需要对客户端的调用进行区分,如果是叶子,对于添加方法和删除方法直接抛出异常即可(面向接口编程原则)
- 扩展性和维护性,服务端可以对代码进行优化,甚至增加功能,客户端都可以不做出改变
阅读全文
0 0
- java设计模式之组合设计模式
- java设计模式之组合模式
- java设计模式之组合模式Composite
- JAVA设计模式之组合模式
- java设计模式之组合模式
- 设计模式之组合模式java实现
- java设计模式之组合模式
- 【Java设计模式】之组合模式
- Java设计模式之组合模式
- Java设计模式泛型化之组合模式
- java设计模式之组合模式
- JAVA设计模式初探之组合模式
- JAVA设计模式初探之组合模式
- java设计模式之组合模式
- java设计模式之组合模式
- JAVA设计模式初探之组合模式
- java设计模式之组合模式篇
- Java设计模式之组合模式
- oracle 常用sql记录.
- TensorFlow-CIFAR10 CNN代码分析
- 中小型机器人开发平台Aopllp的秘密
- spring cloud 版本Dalston.SR4与swagger2.5.0冲突问题的坑
- docker下centos安装ping命令
- java设计模式之组合设计模式
- 程序员,30岁,如何趁 AI 浪潮突破年薪天花板?
- Ubuntu16.04配置licode
- 【探索docker存储之路】一、窥探docker中的volume plugin内幕
- Java
- easyUI combotree加载大量节点数据的处理方式(逐步加载)
- jquery实现全选,全部取消,反选
- 干货 | 深度学习之卷积神经网络(CNN)的模型结构
- C语言基础之常用文件操作1(附代码)