设计模式之组合模式


package com.zwy;

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

/*组合模式:
 * 组合模式就是:一颗树,树上有节点和叶子,节点下面可以拓展节点,但是叶子不能够在拓展
 * 
 * 
 * 定义:组合模式:将对象组合成属性结构以表示:"部分整体"的层次结构,组合模式使得用户对单个对象和组合对象
 * 的使用具有一致性。
 * 当我们发现需求中是体现部分和整体层次的结构是,以及你希望用户可以忽略组合对象和单个对象的不同,同一的使用组合结构中的所有对象就应该考虑使用组合模式了.
 * */
public class CompositionTest {

	
	public static void main(String[] args) {
		Node root = new ComNode("根节点",0);
		
		root.Add(new Leaf("叶节点1",1));
		root.Add(new Leaf("叶节点2",1));
		root.Add(new Leaf("叶节点3",1));
		
		Node node1 = new ComNode("节点1", 1);
		node1.Add(new Leaf("叶节点4",2));
		
		root.Add(node1);
		root.Add(node1);
		root.Display();
	}
}
class Node {
	protected String name ;
	protected int depth ;
	public Node(String name, int depth){
		this.name = name;
		this.depth = depth;
	}
	public void Add(Node node) {
		
	};
	public void Remove(Node node) {
		
	};
	public void Display() {
		
	};
}

class ComNode extends Node {
	protected List<Node> list = null;
	
	public ComNode(String name, int depth) {
		super(name, depth);
		list = new ArrayList<Node>();
	}
	@Override
	public void Add(Node node) {
		list.add(node);
	}

	@Override
	public void Remove(Node node) {
		list.remove(node);
	}

	@Override
	public void Display() {
	//	System.out.println(this.name + ":" + this.depth);
		for(int i = 0 ; i < this.depth;i++){
			System.out.print("--");
		}
		System.out.println(this.name + ":" + this.depth);
		for(Node node : list){
			node.Display();
		}		
	}	
}

class Leaf extends Node {
	public Leaf(String name, int depth) {
		super(name, depth);
	}
	@Override
	public void Display() {
		for(int i = 0 ; i < this.depth;i++){
			System.out.print("--");
		}
		System.out.println(this.name + ":" + this.depth);		
	}	
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值