源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

c# 组合模式

  • 时间:2021-01-27 04:44 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:c# 组合模式
结构图: [img]http://files.jb51.net/file_images/article/201210/20121029135715378.gif[/img] 抽象对象:
[u]复制代码[/u] 代码如下:
    abstract class Component     {         protected string name;         public Component(string name)         {             this.name = name;         }         public abstract void Add(Component c);         public abstract void Remove(Component c);         public abstract void Display(int depth);     }
无子节点的:
[u]复制代码[/u] 代码如下:
    class Leaf : Component     {         public Leaf(string name)             : base(name)         { }         public override void Add(Component c)         {             //throw new NotImplementedException();             Console.WriteLine("Cannot add to a Leaf");         }         public override void Remove(Component c)         {             //throw new NotImplementedException();             Console.WriteLine("Cannot remove to a Leaf");         }         public override void Display(int depth)         {             //throw new NotImplementedException();             Console.WriteLine(new string('-', depth) + name);         }     }
可以有子结点:
[u]复制代码[/u] 代码如下:
    class Composite : Component     {         private List<Component> children = new List<Component>();         public Composite(string name)             : base(name)         { }         public override void Add(Component c)         {             //throw new NotImplementedException();             children.Add(c);         }         public override void Remove(Component c)         {             //throw new NotImplementedException();             children.Remove(c);         }         public override void Display(int depth)         {             //throw new NotImplementedException();             Console.WriteLine(new string('-', depth) + name);             foreach (Component component in children)             {                 component.Display(depth + 2);             }         }     }
 主函数调用:
[u]复制代码[/u] 代码如下:
    class Program     {         static void Main(string[] args)         {             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);             Composite comp2 = new Composite("Composite X");             comp2.Add(new Leaf("Leaf XYA"));             comp2.Add(new Leaf("Leaf XYB"));             comp.Add(comp2);             root.Display(1);             Console.ReadKey();         }     }  
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部