您的位置:首页 > 其它

九、 合成(Composite)模式 --结构模式(Structural Pattern)

2016-02-24 16:26 375 查看
合成模式:有时又叫做部分-整体模式(Part-Whole)。合成模式将对象组织到树结构中,可以用来描述整体与部分的关系。合成模式可以使客户端将单纯元素与复合元素同等看待。

合成模式分为安全式和透明式

安全式合成模式类图:

class CompositePartten2
{
public static void Main(string[] args)
{
Composite root = new Composite("rood");
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);

root.Add(new Leaf("Leaf C"));
// Add and remove a leaf
Leaf l = new Leaf("Leaf D");
root.Add(l);
root.Remove(l);
// Recursively display nodes
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 c);

}

class Composite : Component
{
private ArrayList children = new ArrayList();

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

class Leaf : Component
{
public Leaf(string name) : base(name) { }

public override void Add(Component c)
{
Console.WriteLine("Connot add to leaf");
}

public override void Remove(Component c)
{
Console.WriteLine("Connot remove from a leaf");
}

public override void Display(int c)
{
Console.WriteLine(new String('-', c) + name);
}
}


View Code
运行结果:



使用时注意问题:

1、明显的给出父对象的引用。在子对象里面给出父对象的引用,可以很容易的遍历所有父对象。有了这个引用,可以方便的应用责任链模式。

2、在通常的系统里,可以使用享元模式实现构件的共享,但是由于合成模式的对象经常要有对父对象的引用,因此共享不容易实现。

3、有时候系统需要遍历一个树枝结构的子构件很多次,这 时候 可以考虑把遍历子构件的结果暂时存储在父构件里面作为缓存。

4、关于使用什么数据类型来存储子对象的问题,在示意性的 代码中使用了 ArrayList,在实际系统中可以使用其它聚 集或数组等。

5、客户端尽量不要直接调用树叶类中的方法,而是借助其父 类(Component)的多态性完成调用,这样可以增加代 码的复用性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: