zl程序教程

您现在的位置是:首页 >  后端

当前栏目

c#组合模式

c#模式 组合
2023-06-13 09:14:40 时间
结构图:

抽象对象:
复制代码代码如下:

   abstractclassComponent
   {
       protectedstringname;
       publicComponent(stringname)
       {
           this.name=name;
       }
       publicabstractvoidAdd(Componentc);
       publicabstractvoidRemove(Componentc);
       publicabstractvoidDisplay(intdepth);
   }

无子节点的:
复制代码代码如下:

   classLeaf:Component
   {
       publicLeaf(stringname)
           :base(name)
       {}
       publicoverridevoidAdd(Componentc)
       {
           //thrownewNotImplementedException();
           Console.WriteLine("CannotaddtoaLeaf");
       }
       publicoverridevoidRemove(Componentc)
       {
           //thrownewNotImplementedException();
           Console.WriteLine("CannotremovetoaLeaf");
       }
       publicoverridevoidDisplay(intdepth)
       {
           //thrownewNotImplementedException();
           Console.WriteLine(newstring("-",depth)+name);
       }
   }

可以有子结点:
复制代码代码如下:
   classComposite:Component
   {
       privateList<Component>children=newList<Component>();
       publicComposite(stringname)
           :base(name)
       {}
       publicoverridevoidAdd(Componentc)
       {
           //thrownewNotImplementedException();
           children.Add(c);
       }
       publicoverridevoidRemove(Componentc)
       {
           //thrownewNotImplementedException();
           children.Remove(c);
       }
       publicoverridevoidDisplay(intdepth)
       {
           //thrownewNotImplementedException();
           Console.WriteLine(newstring("-",depth)+name);
           foreach(Componentcomponentinchildren)
           {
               component.Display(depth+2);
           }
       }
   }

 主函数调用:
复制代码代码如下:
   classProgram
   {
       staticvoidMain(string[]args)
       {
           Compositeroot=newComposite("root");
           root.Add(newLeaf("LeafA"));
           root.Add(newLeaf("LeafB"));
           Compositecomp=newComposite("CompositeX");
           comp.Add(newLeaf("LeafXA"));
           comp.Add(newLeaf("LeafXB"));
           root.Add(comp);
           Compositecomp2=newComposite("CompositeX");
           comp2.Add(newLeaf("LeafXYA"));
           comp2.Add(newLeaf("LeafXYB"));
           comp.Add(comp2);
           root.Display(1);
           Console.ReadKey();
       }
   }