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();
}
}
相关文章
- C# winform开发界面美化
- 聊聊 C# 中的 Visitor 模式
- C# XML基本操作
- C#通过Builder模式造车的案例分享
- C#-调用浏览器打开网页
- c#面试题抽象类和接口的区别-金三银四面试:C#程序员经常遇到的30道基础面试题,想你所想
- C# CSV 导出详解编程语言
- C与MySQL结合实现处理图片的功能(c# mysql 图片)
- c#类型转换
- c#适配器模式
- asp.netc#采集需要登录页面的实现原理及代码
- 深入C#字符串和享元(Flyweight)模式的使用分析
- 深入c#工厂模式的详解
- 操作xml,将xml数据显示到treeview的C#代码
- c#保存窗口位置大小操作类(序列化和文件读写功能)
- c#使用简单工厂模式实现生成html文件的封装类分享
- C#Ini文件操作实例
- C#装饰者模式实例分析
- C#设计模式之观察者模式实例讲解
- C#中DataSet转化为实体集合类的方法
- 浅谈C#设计模式之工厂模式
- C#中的IDisposable模式用法详解
- C#单例模式(SingletonPattern)实例教程
- C#观察者模式(ObserverPattern)实例教程
- C#复合模式(CompositePattern)实例教程