java设计模式----组合模式

  • 定义

        组合模式(Composite),将对象组合成树形结构以表示‘部分-整体’的层次关系(树状结构)。组合模式使得用户对单个对象和组合对象使用具有一致性。 

  • 意图

        希望用户可以忽略单个对象和组合对象的区别,统一使用组合结构中的所有对象(封装变化的思想)。 

  • 结构图

composite0

图1组合模式(Composite)结构图 

  • 参与者

        Component 

        它是一个抽象角色,为对象的组合提供统一的接口。 

        为其派生类提供默认的行为。 

        通过该接口来访问和管理Child Components(节点后继)。 

        通过该接口来访问Parent Components(节点前驱)。 

        Leaf 

        代表参加组合的叶子对象(叶子没有后继)。 

        定义组成原始对象的行为。 

        Composite 

        定义非叶子对象的行为。 

        实现Component中的孩子操作行为(如:Add(),Remove() 等)。 

 在使用组合模式中需要注意一点也是组合模式最关键的地方:叶子对象和组合对象实现相同的接口。这就是组合模式能够将叶子节点和对象节点进行一致处理的原因。

组合对象的关键在于它定义了一个抽象构建类,它既可表示叶子对象,也可表示容器对象,客户仅仅需要针对这个抽象构建进行编程,无须知道他是叶子对象还是容器对象,都是一致对待。

建一个抽象类:

package composite;

public abstract class Component {
	protected String name;

	public Component(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public abstract void display();
}

 建一个子类容器:

package composite;

import java.util.ArrayList;
import java.util.List;

public class Composite extends Component {
	private List<Component> childen = new ArrayList<Component>();
	public Composite(String name){
		super(name);
	}

	public void remove(Component c) {
		this.childen.remove(c);

	}

	public void add(Component c) {
		this.childen.add(c);
	}

	@Override
	public void display() {
		for (Component c : childen){
			c.display();
		}
		
	}

}

 可以看到子类容器增加了两个方法,并重写了父类的display方法。

新增一个叶子节点:

package composite;

public class Leaf extends Component {
	public Leaf(String name) {
		super(name);
	}

	@Override
	public void display() {
		System.out.println("this leaf's name is " + super.getName());

	}

}

 测试下

package composite;

/**
 * 组合模式
 * 
 * @author mercy
 *
 */
public class Test {
	public static void main(String[] args) {
		Composite c=new Composite("容器对象");
		Leaf l=new Leaf("叶子节点");
		c.add(l);
		c.display();
	}

}

 结果:

this leaf's name is 叶子节点
原文地址:https://www.cnblogs.com/JAYIT/p/5010294.html