Welcome

首页 / 软件开发 / .NET编程技术 / .net设计模式实例之组合模式(Composite Pattern)

.net设计模式实例之组合模式(Composite Pattern)2011-04-21 博客园 灵动生活一、组合模式简介(Brief Introduction)

组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户 对单个对象和组合对象的使用具有一致性。

二、解决的问题(What To Solve)

解决整合与部分可以被一致对待问题。

三、组合模式分析(Analysis)1、组合模式结构

Component类:组合中的对象声明接口,在适当情况下,实现所有类共有接口的行为。声 明一个接口用于访问和管理Component的子部件

Leaf类:叶节点对象,叶节点没有子节点。由于叶节点不能增加分支和树叶,所以叶节点 的Add和Remove没有实际意义。

有叶节点行为,用来存储叶节点集合

Composite类:实现Componet的相关操作,比如Add和Remove操作。

children:用来存储叶节点集合

2、源代码

1、抽象类Component

public 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 Diaplay(int depth);
}