组合模式【大话设计模式DEMO】

组合模式将对象组合成树形结构以表示“部分-整体”的层次结构。组合模式使得用户对单个对象和组合对象的使用具有一致性。
整体与部分可以被一致对待。(看上去也有递归的感觉)

类设计图:

2010033010571865.png

DEMO代码:

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
class RunCompositePattern
{

static void Main( string [] args)
{
Composite root
= new Composite( " root " );
root.Add(
new Leaf( " A " ));
root.Add(
new Leaf( " B " ));

Composite comp
= new Composite( " Compostie X " );
comp.Add(
new Leaf( " Leaf XA " ));
comp.Add(
new Leaf( " Leaf XB " ));

root.Add(comp);

Composite comp2
= new Composite( " Compostie XY " );
comp2.Add(
new Leaf( " Leaf XYA " ));
comp2.Add(
new Leaf( " Leaf XYB " ));

comp.Add(comp2);

root.Add(
new Leaf( " C " ));
Leaf leaf
= new Leaf( " D " );
root.Add(leaf);
root.Remove(leaf);
root.Display(
1 );
Console.ReadKey();

}
}

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(
" 不能为叶子节点添加子元素 " );
}

public override void Remove(Component c)
{
Console.WriteLine(
" 不能从叶子节点删除子元素 " );
}
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);
foreach (Component item in children)
{
item.Display(depth
+ 2 );
}
}
}

 

 

 

运行结果:

2010033010582135.png

 

转载于:https://www.cnblogs.com/shineqiujuan/archive/2010/03/30/1700384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值