手机
当前位置:查字典教程网 >编程开发 >C#教程 >c# 组合模式
c# 组合模式
摘要:结构图:抽象对象:复制代码代码如下:abstractclassComponent{protectedstringname;publicCom...

结构图:

c# 组合模式1

抽象对象:

复制代码 代码如下:

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);

}

无子节点的:

复制代码 代码如下:

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);

}

}

可以有子结点:

复制代码 代码如下:

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);

}

}

}

主函数调用:

复制代码 代码如下:

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();

}

}

【c# 组合模式】相关文章:

c# 获得局域网主机列表实例

剖析设计模式编程中C#对于组合模式的运用

c# 备忘录模式

深入c#工厂模式的详解

c# 代理模式

c#匹配整数和小数的正则表达式

C# Console类的具体用法

C# 排序算法之堆排序

C#数组初始化简析

c# 类型转换

精品推荐
分类导航