您的位置:首页 > 其它

Composite 组合(结构型模式)

2009-12-17 23:20 316 查看
代码

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

using System.Collections;

namespace testWpf
{
//使用了组合模式

public interface IBox
{
void process();
void Add(IBox box);
void Remove(IBox box);
}

public class SingleBox : IBox
{
public void process()
{
//1.Do Something for myself
//... ...
}

//不是容器对象,不支持的方法可以选择抛出异常
public void Add(IBox box)
{
throw new Exception("not supported");
}
public void Remove(IBox box)
{
throw new Exception("not supported");
}
}

public class ContainerBox : IBox
{
ArrayList list = null;

public void add(IBox box)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(box);
}

public void Remove(IBox box)
{
if (list == null)
{
throw new Exception("error");
}
list.Remove(box);
}

public void process()
{
//1.Do Something for myself
//... ...

//2.Do process for the box in the list
if (list != null)
{
foreach (IBox box in list)
{
box.Process(); //递归
}
}
}
}

/// <summary>
/// 客户代码
/// </summary>
class App
{
public static void Main()
{
IBox box = Factor.GetBox();

//客户代码与抽象接口进行耦合,这是面向对象设计的导向
box.process();

}
}
}

Composite模式的几个要点

Composite模式采用树形结构来实现普遍存在的对象容器,从而将“一对多”的关系转化为“一对一”的关系,使得客户代码可以一致地处理对象和对象容器,无需关心处理的是单个的对象,还是组合的对象容器。
将“客户代码与复杂的对象容器结构”解耦是Composite模式的核心思想,解耦之后,客户代码将与纯粹的抽象接口——而非对象容器的复内部实现结构——发生依赖关系,从而更能“应对变化”。
Composite模式中,是将“Add和Remove等和对象容器相关的方法”定义在“表示抽象对象的Component类”中,还是将其定义在“表示对象容器的Composite类”中,是一个关乎“透明性”和“安全性”的两难问题,需要仔细权衡。这里有可能违背面向对象的“单一职责原则”,但是对于这种特殊结构,这又是必须付出的代价。ASP.NET控件的实现在这方面为我们提供了一个很好的示范。
Composite模式在具体实现中,可以让父对象中的子对象反向追溯;如果父对象有频繁的遍历需求,可使用缓存技巧来改善效率。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: