設計模式----組合模式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

相關文章
相關標籤/搜索