组合模式

组合模式:

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

/**
 * 组合中的对象声明接口,在适当情况下,实现所有类共有接口的默认形为。
 * 声明一个接口用于访问和管理Component的子部件。
 *
 */
public abstract class Component {
	
	private String name;
	
	public Component(String name){
		this.name = name;
	}	
	// 增加树叶或树枝
	public abstract void add(Component component);
	// 移除树叶或树枝
	public abstract void remove(Component component);
	public abstract void display(int depth);
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

/**
 * 定义有枝节点行为,用来存储子部件,在Component接口中实现与子部件有关的操作。
 *
 */
public class Composite extends Component{
	
	private List<Component> childerns = new ArrayList<Component>();	
	
	public Composite(String name) {
		super(name);
	}

	@Override
	public void add(Component component) {
		childerns.add(component);		
	}

	/**
	 * 显示其枝节点名称,并对其下级进行遍历
	 */
	@Override
	public void display(int depth) {
		for(int i=0;i<depth;i++){
			System.out.print("-");
		}
		System.out.println(this.getName());	
		
		// 遍历子节点
		for(Component component:childerns){
			component.display(depth+2);
		}		
	}
	@Override
	public void remove(Component component) {
		childerns.remove(component);		
	}
}

 

/**
 * 叶节点对象:叶节点没有子结点
 *
 */
public class Leaf extends Component{

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

	@Override
	public void add(Component component) {
		System.out.println("cannot add to a leaf.");		
	}

	@Override
	public void display(int depth) {
		for(int i=0;i<depth;i++){
			System.out.print("-");
		}
		System.out.println(this.getName());		
	}
	
	@Override
	public void remove(Component component) {
		System.out.println("cannot remove  from a leaf.");			
	}
}

 

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		// 生成树根,根上长出两叶
		Composite root = new Composite("root");
		root.add(new Leaf("leaf A"));
		root.add(new Leaf("leaf B"));
		
		// 根上再长出分枝Composite X,分枝上也长出两叶
		Composite comp = new Composite("Composite X");
		comp.add(new Leaf("leaf XA"));
		comp.add(new Leaf("leaf XB"));
		root.add(comp);
		
		// Composite X分枝上再长出分枝Composite XY,分枝上也长出两叶
		Composite comp2 = new Composite("Composite XY");
		comp2.add(new Leaf("leaf XYA"));
		comp2.add(new Leaf("leaf XYB"));
		comp.add(comp2);
		
		//根上又长出两叶
		root.add(new Leaf("leaf C"));		
		Leaf leafD = new Leaf("leaf D");
		root.add(leafD);
		
		// D叶子被刮掉了
		root.remove(leafD);
		
		// 显示大树
		root.display(1);
	}

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值