2019独角兽企业重金招聘Python工程师标准>>>
一、什么是组合模式?
组合模式(Composite)定义:将对象组合成树形结构以表示‘部分---整体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性.
类型:结构型模式
顺口溜:适装桥组享代外
二、组合模式UML
三、JAVA代码实现
package com.amosli.dp.composite;public abstract class Component {protected String name;public Component(String name) {this.name = name;}public abstract void add(Component c);public abstract void remove(Component c);public abstract void display(int depth);
}package com.amosli.dp.composite;import java.util.ArrayList;
import java.util.List;public class Composite extends Component {public Composite(String name) {super(name);}private List<Component> components= new ArrayList<Component>();@Overridepublic void add(Component c) {components.add(c);}@Overridepublic void remove(Component c) {components.remove(c);}@Overridepublic void display(int depth) {System.out.println(Util.concat("-", depth++).concat(name));for (Component component : components) {component.display(depth+1);}}}package com.amosli.dp.composite;public class Leaf extends Component {public Leaf(String name) {super(name);}@Overridepublic void add(Component c) {System.out.println("this is leaf,cannot be added!");}@Overridepublic void remove(Component c) {System.out.println("this is leaf,cannot be removed!");}@Overridepublic void display(int depth) {System.out.println(Util.concat("-", depth).concat(name));}}package com.amosli.dp.composite;public class Util {public static String concat(String str, int num) {StringBuilder sb = new StringBuilder();for(int i=0;i<num;i++){sb.append(str);}return sb.toString();}public static void main(String[] args) {System.out.println(concat("-", 3));}
}package com.amosli.dp.composite;public class Client {public static void main(String[] args) {Component c = new Composite("root");c.add(new Leaf("leaf1"));c.add(new Leaf("leaf2"));Component sub = new Composite("sub1");sub.add(new Leaf("grand1"));sub.add(new Leaf("grand2"));Component sub2 = new Composite("sub2");sub2.add(new Leaf("grand3"));sub2.add(new Leaf("grand4"));c.add(sub);c.add(sub2);c.display(1);}
}
输出结果:
四、使用场景
1.你想表示对象的部分-整体层次结构
2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。
引用大话设计模式的片段:“当发现需求中是体现部分与整体层次结构时,以及你希望用户可以忽略组合对象与单个对象的不同,统一地使用组合结构中的所有对象时,就应该考虑组合模式了。”
五、源码地址
本系列文章源码地址,https://github.com/amosli/dp 欢迎Fork & Star !!