十六、组合模式 Composite

一、定义

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

应用:当你发现需求中是体现部分与真题层次的结构是,以及你希望用户可以忽略组合对象与单个对象的不同,统一使用组合结构中的所有对象时,就应该考虑使用组件设计模式。

二、结构图


三、代码示例

/**
 * @use 测试组合模式
 * @author lattice
 * @date 2017-01-03
 */
public class CompositeTest {

	public static void main(String[] args) {
		Composite root=new Composite("root");
		root.add(new Leaf("leaf A"));

		Composite comp=new Composite("composite A");
		comp.add(new Leaf("leaf A of composite A"));
		comp.add(new Leaf("leaf B of composite A"));
		
		root.add(comp);
		
		root.add(new Leaf("leaf B"));
		root.display(1);
		
		/**
		 * 输出结果
		 *  
		    -root
			---leaf A
			---composite A
			-----leaf A of composite A
			-----leaf B of composite A
			---leaf B

		 */
	}
}

abstract class Component {
	protected String name;

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

	public String getString(String str, int number) {
		String result = "";
		for (int i = 0; i < number; i++) {
			result += str;
		}
		return result;
	}

	public abstract void add(Component c);

	public abstract void remove(Component c);

	public abstract void display(int depth);
}

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

	public void add(Component c) {
		System.out.println("connot add to a leaf");
	}

	public void remove(Component c) {
		System.out.println("connot remove from a leaf");
	}

	public void display(int depth) {
		System.out.println(getString("-", depth) + name);
	}
}

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

	public void add(Component c) {
		childrens.add(c);
	}

	public void remove(Component c) {
		childrens.remove(c);
	}

	public void display(int depth) {
		System.out.println(getString("-", depth) + name);
		for(Component sb:childrens){
			sb.display(depth+2);
		}
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值