head first 设计模式学习随笔(10)----组合模式

所谓组合模式----允许将对象组合形成树形结构来表现“整体/部分”层次结构。组合能让客户以一致的方式处理个别对象以及对象集合

个人认为Xml数据的格式就很类似于组合模式,而XmlNode类适合于组合模式的描述,以下我将以长江源头描述起,来说明组合模式

 

Code
/// <summary>
/// 组合模式 抽象类
/// </summary>
public abstract class Component
{
public abstract string GetInfo();
public abstract List<Component> GetChilds();
public abstract void AddChild(Component com);
public abstract void RemoveChild(Component com);

/// <summary>
/// 打印全部信息
/// </summary>
public void PrintAll()
{
Print(
this,0);
}

/// <summary>
/// 递归方法遍历所有
/// </summary>
/// <param name="com"></param>
/// <param name="i"></param>
private void Print(Component com,int i)
{
Console.WriteLine(GetTab(i)
+ com.GetInfo());
List
<Component> childs =com.GetChilds();
if (childs != null)
{
foreach (Component list in childs)
Print(list,
++i);
}
}

/// <summary>
/// 这里是tab 为了使得层次更加清晰
/// </summary>
/// <param name="i"></param>
/// <returns></returns>
private string GetTab(int i)
{
string tab="";
for (int j = 0; j < i; j++)
tab
+= "\t";
return tab;
}
}

/// <summary>
/// 河 可以有分支溪流组成
/// </summary>
public class River : Component
{
List
<Component> Rivers;
string info;

public River(string info)
{
Rivers
= new List<Component>();
this.info = info;
}

public override string GetInfo()
{
return info;
}

public override List<Component> GetChilds()
{
return this.Rivers;
}

public override void AddChild(Component com)
{
Rivers.Add(com);
}

public override void RemoveChild(Component com)
{
Rivers.Remove(com);
}
}

/// <summary>
/// 溪流 没有分支啦
/// </summary>
public class Rivulet : Component
{
string info;

public Rivulet(string info)
{
this.info = info;
}

public override string GetInfo()
{
return info;
}

public override List<Component> GetChilds()
{
return null;
}

#region 以下2个方法不实现

public override void AddChild(Component com)
{
throw new NotImplementedException();
}

public override void RemoveChild(Component com)
{
throw new NotImplementedException();
}

#endregion

}


class Program
{
static void Main(string[] args)
{
River changjiang
= new River("长江");
River yalongjiang
= new River("雅砻江");
River minjiang
= new River("岷江");

Rivulet tuotuohe
= new Rivulet("沱沱河");
Rivulet tongtianhe
= new Rivulet("通天河");
Rivulet daduhe
= new Rivulet("大渡河");
Rivulet jialingjiang
= new Rivulet("嘉陵江");
Rivulet wujiang
= new Rivulet("乌江");
Rivulet yuanjiang
= new Rivulet("沅江");
Rivulet xiangjiang
= new Rivulet("湘江");
Rivulet hanjiang
= new Rivulet("汉江");
Rivulet ganjiang
= new Rivulet("赣江");
Rivulet huangpujiang
= new Rivulet("黄浦江");

yalongjiang.AddChild(daduhe);
yalongjiang.AddChild(jialingjiang);
yalongjiang.AddChild(wujiang);

minjiang.AddChild(yuanjiang);
minjiang.AddChild(xiangjiang);
minjiang.AddChild(hanjiang);
minjiang.AddChild(ganjiang);

changjiang.AddChild(tuotuohe);
changjiang.AddChild(tongtianhe);
changjiang.AddChild(yalongjiang);
changjiang.AddChild(minjiang);
changjiang.AddChild(huangpujiang);

changjiang.PrintAll();

Console.Read();
}
}

 

head first 设计模式学习随笔(10)----组合模式

你可能感兴趣的:(first)