您的位置:首页 > 其它

Core Design Patterns(4) Composite 组合模式

2008-03-07 22:21 288 查看
VS 2008

组合模式使得我们可以以同样的方式看待单一Comonent和Component集合。

也就是,单一对象和该对象的组合具有相同的抽象行为。

组合模式通常用于构建树型结构。

1. 模式UML图

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

DepartmentLeaf.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using DesignPattern.Composite.BLL;

namespace DesignPattern.Composite {

{

{

{ DepartmentId=1, DepartmentName="市政局" });

{ DepartmentId = 2, DepartmentName = "市管处" });

{ DepartmentId = 3, DepartmentName = "公路处" });

{ DepartmentId = 4, DepartmentName = "公路署" });

c2.Add(s1);

j1.Add(c1);

j1.Add(c2);

Console.WriteLine(j1.GetChildCount().ToString());

Console.WriteLine(c1.GetChildCount().ToString());

Console.WriteLine(c2.GetChildCount().ToString());

Console.WriteLine(s1.GetChildCount().ToString());

}

}

}

Output




3. 思考

对于组合模式,通常可以将前述的UML进行退还,我们甚至可以不要Leaf类,为了灵活扩展性,每个叶子都可以演变为树枝。

对于本例的部门树型结构其实只是选择了一个最简单的行为进行实现,真正的树,需要实现的行为还远不止这些。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: