设计模式----组合模式UML和实现代码

1、什么是组合模式?

组合模式(Composite)定义:将对象组合成树形结构以表示‘部分---总体’的层次结构。组合模式使得用户对单个对象和组合对象的使用具备一致性.java

类型:结构型模式git

顺口溜:适装桥享代外github

2、组合模式UML

3、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>();
	@Override
	public void add(Component c) {
		components.add(c);
	}

	@Override
	public void remove(Component c) {
		components.remove(c);
	}

	@Override
	public 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);
	}

	@Override
	public void add(Component c) {
		System.out.println("this is leaf,cannot be added!");
	}

	@Override
	public void remove(Component c) {
		System.out.println("this is leaf,cannot be removed!");
	}

	@Override
	public 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);

	}
}


输出结果:设计模式

4、使用场景

1.你想表示对象的部分-总体层次结构

2.你但愿用户忽略组合对象与单个对象的不一样,用户将统一地使用组合结构中的全部对象。


       引用大话设计模式的片断:“当发现需求中是体现部分与总体层次结构时,以及你但愿用户能够忽略组合对象与单个对象的不一样,统一地使用组合结构中的全部对象时,就应该考虑组合模式了。”app


5、源码地址

本系列文章源码地址,https://github.com/amosli/dp  欢迎Fork  & Star !!ide

相关文章
相关标签/搜索