组合模式

本文通过一个具体的例子详细介绍了组合模式在C#中的应用。利用组合模式可以将对象组织成树形结构来表示整体-部分的层次结构,使得客户端能够一致地处理单个对象以及组合对象。文章展示了如何创建组件基类及其实现,包括叶子节点和复合节点,并演示了如何构建和遍历这些节点。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*

组合模式
*
* 树型节点管理

*/
namespace App_MYCS.HDL_SJMS.ZHMS
{
class my_ZHMS
{
public void dy()
{
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 Y");
comp2.Add(new Leaf("leaf Ya"));
comp2.Add(new Leaf("leaf Yb"));

comp.Add(comp2);

root.Add(new Leaf("leaf c"));

root.Display(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)
{
Console.WriteLine("Cannot add to a leaf");
}

public override void Remove(Component c)
{
Console.WriteLine("Cannot Remove to a leaf");
}

public override void Display(int depth)//显示
{
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)
{
children.Add(c);
}

public override void Remove(Component c)
{
children.Remove(c);
}

public override void Display(int depth)//显示
{
Console.WriteLine(new String('-', depth) + name);//叶节点的具体方法 显示名称和级别

if (children != null && children.Count > 0)
{
foreach (Component cp in children)
{
cp.Display(depth + 2);
}
}
}
}

}

转载于:https://www.cnblogs.com/longkai178/p/5815127.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值