设计模式之组合模式

遍历一棵树

在基于关系型数据库的应用程序中,一对多的关系是在太多了,那么如何来轻松地遍历一棵树呢?
我们今天来介绍一个专门为树形结构而生的设计模式,组合模式。
一棵树包括分支节点和叶子节点,我们让他们实现同样的接口

public interface IComponent
{
	string GetInfo();
}

定义分支节点

public class Composite : IComponent
{
	private string name;
	public Composite(string _name)
	{
		this.name = _name;
	}

	private List<IComponent> children = new List<IComponent>();

	public string GetInfo()
	{
		return string.Format("我是{0},我有{1}个子节点", name, children.Count);
	}

	/// <summary>
	/// 添加子节点
	/// </summary>
	/// <param name="child"></param>
	public void AddChild(IComponent child)
	{
		children.Add(child);
	}

	/// <summary>
	/// 移除子节点
	/// </summary>
	/// <param name="child"></param>
	public void RemoveChild(IComponent child)
	{
		children.Remove(child);
	}

	public List<IComponent> GetChildren()
	{
		return children;
	}
}

下面是叶子节点

public class Leaf:IComponent
{
	private string name;
	public Leaf(string _name)
	{
		this.name = _name;
	}
	public string GetInfo()
	{
		return "我是" + name;
	}
}

组合模式到底是如何实现遍历一棵树的呢?下面来看场景类

class Program
{
	static void Main(string[] args)
	{
		//先来组织一棵树,根节点包含manage1和manage2,manager1包括员工1和员工2,
		//manager2包括员工3和员工4
		Composite root = new Composite("Boss");
		Composite manager1 = new Composite("Manager1");
		Composite manager2 = new Composite("Manager2");

		IComponent empl1 = new Leaf("员工1");
		IComponent empl2 = new Leaf("员工2");
		IComponent empl3 = new Leaf("员工3");
		IComponent empl4 = new Leaf("员工4");

		manager1.AddChild(empl1);
		manager1.AddChild(empl2);

		manager2.AddChild(empl3);
		manager2.AddChild(empl4);

		root.AddChild(manager1);
		root.AddChild(manager2);

		Console.WriteLine( root.GetInfo());
		DisplayTreeInfo(root);
		
		Console.ReadKey();
	}

	//遍历函数,递归调用
	static void DisplayTreeInfo(Composite composite)
	{
		foreach (IComponent item in composite.GetChildren())
		{
			if (item is Composite)
			{
				Composite c = item as Composite;
				Console.WriteLine(c.GetInfo());
				DisplayTreeInfo(c);
			}
			else
			{
				Console.WriteLine(item.GetInfo());
			}
		}
	}
}

运行结果:
我是Boss,我有2个子节点
我是Manager1,我有2个子节点
我是员工1
我是员工2
我是Manager2,我有2个子节点
我是员工3
我是员工4

认识组合模式

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

在上面的例子中,无论是分支节点还是叶子节点,都实现了同一个接口IComponent,这样的好处是,客户端不需要区分是分支节点还是叶子节点,都可以调用GetInfo方法来完成某个功能。

组合模式的缺点也很明显,违反了依赖倒置原则,客户端在使用时,尽管都可以调用IComponent的GetInfo方法,但是,在遍历时,还是用到了具体的类Composite和Leaf。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值