Composite 组合模式

模式定义
在实际的编程中常常出现这样的情形:A对象包含了另外一个对象B,而B又包含了其他对象C和D,好比一棵树,树枝上有树枝,树枝上再有小树枝或树叶,这样的层次结构可以用Composite模式来实现。因此Composite模式将对象组合成树形结构以表示“部分-整体”的层次结构,使得用户对单个对象和组合对象的使用具有一致性。

 

使用范围

  • 多个对象之间存在层次组合的结构
  • 使组合对象或者单个对象对于客户而言具有访问的一致性

使用方法
将组合对象与单个对象的共有属性或方法剥离出一个抽象类,组合对象与单个对象分别继承该抽象类并实例化。

举例说明
我们用Composite来描述一棵树。树是树枝和树叶的抽象,树有名字(可能为树枝,也可能为树叶,体现为具体的子类),用add方法表示树枝可以有其他树枝或树叶,用printAll表述列举一棵树的完整结构。

import java.util.ArrayList;

public abstract class Tree {
	protected ArrayList list = new ArrayList();
	protected String name = null;

	public Tree(){};

	public abstract void add(Tree t);
	public abstract void remove(Tree t);
	public abstract void printAll();
}

树枝节点:

public class Branch extends Tree {

	public Branch(String name){
		this.name = name;
	}
	public void add(Tree t) {
		list.add(t);
	}

	public void printAll() {
		for (int i=0; i< list.size(); i++){
			System.out.println(name);
			System.out.println("|---");
			((Tree)list.get(i)).printAll();
		}

	}

	public void remove(Tree t) {
		if (list.contains(t))
			list.remove(t);

	}

}

树叶节点,注意树叶属于最低级的一个树,不再包含其他树的实例对象,因此不存在add方法。

public class Leaf extends Tree {

	public Leaf(String name){
		this.name = name;
	}
	public void add(Tree t) {
		return;

	}

	public void printAll() {
		System.out.println(name);
	}

	public void remove(Tree t) {
		return;
	}

}

最后,给出一棵树的完整结构,比如:

通过Tree.add方法在树枝上加树枝或加叶,即能实现一棵完整的树。

public class Client {
	public static void main(String args[]){
		Tree root= new Branch("Root");
		Tree branch1 = new Branch("B1");
		Tree branch2 = new Branch("B2");
		Tree branch3 = new Branch("B3");
		Tree branch4 = new Branch("B4");
		Tree leaf1 = new Leaf("L1");
		Tree leaf2 = new Leaf("L2");
		Tree leaf3 = new Leaf("L3");

		root.add(branch1);
		root.add(branch3);
		branch1.add(branch2);
		branch1.add(leaf1);
		branch2.add(branch4);
		branch2.add(leaf2);
		branch3.add(leaf3);

		root.printAll();
	}
}

类结构示意
该样例的类结构如下:

下载示例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值