设计模式笔记——Composite

组合模式Composite

将对象组合成熟形结构已表示整体和部分的层次结构,用户对单个对象和组合对象的使用具有一致性。

 

 

需求中体现部分和整体的层次结构,并且希望用户可以忽略组合对象和单个对象的不同,统一使用组合结构的所有对象(具有一致性),就应该考虑组合模式

 

组合模式让用户可以一致的使用组合结构和单个对象,不用判断到底是在处理一个叶结点还是处理一个组合节点,也不用为定义组合而写一些选择判断语句。


package composite.pattern;

public class CompositePattern {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Composite root=new Composite("root");
		root.Add(new Leaf("Leaf_A"));
		
		Composite node1=new Composite("node_B");
		root.Add(node1);
		
		root.Add(new Leaf("Leaf_C"));
		
		Composite node2=new Composite("node_AB");
		
		node1.Add(node2);
		node1.Add(new Leaf("Leaf_AC"));
		
		node2.Add(new Leaf("Leaf_ABD"));
		node2.Add(new Leaf("Leaf_ABE"));
		
		root.Display(1);
	}

}

package composite.pattern;

public abstract class Compoment {
	
	private String name;
	
	public Compoment(String name){
		this.setName(name);
	}
	
	public abstract void Add(Compoment compoment);
	public abstract void Remove(Compoment compoment);
	public abstract void Display(int depth);

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

	public String getName() {
		return name;
	}


}

package composite.pattern;

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

public class Composite extends Compoment {

	private List<Compoment> children = new ArrayList<Compoment>();

	public Composite(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void Add(Compoment compoment) {
		// TODO Auto-generated method stub
		children.add(compoment);
	}

	@Override
	public void Display(int depth) {
		// TODO Auto-generated method stub
		for (int i = 0; i < depth; i++) {
			System.out.print("-");
		}
		System.out.println(this.getName());
		for (Compoment c : children) {
			c.Display(depth + 2);
		}
	}

	@Override
	public void Remove(Compoment compoment) {
		// TODO Auto-generated method stub
		children.remove(compoment);
	}

}

package composite.pattern;

public class Leaf extends Compoment {

	public Leaf(String name) {
		super(name);
	}

	@Override
	public void Add(Compoment compoment) {
		// TODO Auto-generated method stub
		System.out.println("Can not Add");
	}

	@Override
	public void Display(int depth) {
		// TODO Auto-generated method stub
		for (int i = 0; i < depth; i++) {
			System.out.print("-");
		}
		System.out.println(this.getName());
	}

	@Override
	public void Remove(Compoment compoment) {
		// TODO Auto-generated method stub
		System.out.println("Can not Remove");

	}

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值