标签:
对象以树形结构组织起来,以达成“部分-整体”的层次结构
class Program
{
static void Main(string[] args)
{
CompositionEquipment equip = new CompositionEquipment();
equip[0] = new Guest(1,"1");
equip[-1] = new Guest(2, "2");
equip[2] = new Guest(3, "3");
equip[2] = new Guest(4, "4");
IEnumerator ietor = equip.GetEnumerator();
while (ietor.MoveNext())
{
Console.WriteLine(((Guest)(ietor.Current)).id);
Console.WriteLine(((Guest)(ietor.Current)).name);
}
foreach (Guest gu in equip)
{
Console.WriteLine(gu.id);
Console.WriteLine(gu.name);
}
Console.ReadKey();
}
}
public struct Guest {
public int id;
public string name;
public Guest(int id, string name)
{
this.id = id;
this.name = name;
}
}
public class CompositionEquipment : IEnumerator
{
private List<object> equip = new List<object>();
public object this[int index]{
get{return equip[index];}
set{equip.Add(value);}
}
public int Count(){
return equip.Count;
}
public IEnumerator GetEnumerator()
{
return new CompositionIterator(this);
}
public object Current
{
get { throw new NotImplementedException(); }
}
public bool MoveNext()
{
throw new NotImplementedException();
}
public void Reset()
{
throw new NotImplementedException();
}
}
public class CompositionIterator:IEnumerator
{
private CompositionEquipment equip;
private int currentindex;
public CompositionIterator(CompositionEquipment equip)
{
this.equip = equip;
this.currentindex = -1;
}
object IEnumerator.Current
{
get {return equip[currentindex]; }
}
public bool MoveNext()
{
currentindex++;
return equip.Count() > currentindex;
}
public void Reset()
{
currentindex = -1;
}
}
设计模式之composit
标签:
原文地址:http://www.cnblogs.com/sky7728/p/4447508.html