结构型模式-组合模式课件.ppt
文本预览下载声明
8.2 组合模式(COMPOSITE) ;;;;;;;模式原型代码 :;class Composite : Component
??{
????private ListComponent _children = new ListComponent();
?
????// Constructor
????public Composite(string name)????: base(name)????{????}
?
????public override void Add(Component component)????{
??????_children.Add(component);
????}
?
????public override void Remove(Component component)????{
??????_children.Remove(component);
????}
?
????public override void Display(int depth)????{
??????Console.WriteLine(new String(-, depth) + name);?
??????// Recursively display child nodes
??????foreach (Component component in _children)??????{
????????component.Display(depth + 2);
??????}
????}
??};class Leaf : Component
??{
????// Constructor
????public Leaf(string name)
??????: base(name)
????{
????}
?
????public override void Add(Component c)
????{
??????Console.WriteLine(Cannot add to a leaf);
????}
?
????public override void Remove(Component c)
????{
??????Console.WriteLine(Cannot remove from a leaf);
????}
?
????public override void Display(int depth)
????{
??????Console.WriteLine(new String(-, depth) + name);
????}
??}
} ;?static void Main()
????{
??????// Create a tree structure
??????Composite root = new Composite(root);
??????root.Add(new Leaf(Leaf A));
??????root.Add(new Leaf(Leaf B));
?
??????Composite comp = new Composite(Composite X);
??????comp.Add(new Leaf(Leaf XA));
??????comp.Add(new Leaf(Leaf XB));
?
??????root.Add(comp);
??????root.Add(new Leaf(Leaf C));
?
??????// Add and remove a leaf
??????Leaf leaf = new Leaf(Leaf D);
??????root.Add(leaf);
??????root.Remove(leaf);
?
??????// Recursively display tree
??????root.Display(1);
?
??????// Wait for user
??????Console.ReadKey();
????};;;;;;;;;;;;;;;;;;;;;;;;
显示全部