您的位置:首页 > 编程语言 > C#

C#面向对象设计模式纵横谈 笔记9 Composite 组合(结构型模式)

2011-09-12 15:08 477 查看
对象容器的问题

在面向对象系统中,我们常会遇到一类具有“容器”特征的对象——即它们在充当对象的同时,又是其他对象的容器。

public class SingleBox: IBox
{
  public void process() { ……}
}
public class ContainerBox :IBox
{
  public void process(){……}
  public ArrayList getBoxes(){……}
}


如果我们要对这样的对象容器进行处理:

(客户程序,它必须知道ContainerBox的内部结构。此段客户代码与对象结构代码耦合度太紧,最好是依赖抽象接口的,如:依赖IBox接口。)

IBox box=Factory.GetBox();
if (box is ContainerBox)
{
  box.process();
  ArrayList list= ((ContrainerBox) box).GetBoxes();
  …… // 将面临比较复杂的递归处理
}
else if( box is SingleBox)
{
  box.process();
}


动机(Motivation)

上述描述的问题根源在于:客户代码过多地依赖于对象容器复杂的内部实现结构,对象容器内部实现结构(而非抽象接口)的变化将引起客户代码的频繁变化,带来了代码的维护性、扩展性等弊端。

如何将“客户代码与复杂的对象容器结构”解耦?让对象容器自己来实现自身的复杂结构,从而使得客户代码就像处理简单对象一样来处理复杂的对象容器?

意图(Intent)

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

例说Composite应用 Codes in .NET

1)

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


2)单个的对象

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

public void Add(IBox box)
{
throw new UnSuporttedException();
}

public void Remove(IBox box)
{
throw new UnSuporttedException();
}
}


3)盒子对象容器

public class ContailerBox : IBox
{
ArrayList list;

public void Add(IBox box)
{
if (list == null)
{
list = new ArrayList();
}
list.Add(box);
}
public void Remove(IBox box)
{
if (list == null)
{
throw new ArgumentNullException();
}
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 item in list)
{
item.Process();
}
}
}
public IList GetBoxes()
{
return list;
}
}


结构(Structure)



Composite模式的几个要点

1)Composite模式采用树形结构来实现普遍存在的对象容器,从而将“一对多”的关系转化为“一对一”的关系,使得客户代码可以一致地处理对象和对象容器,无需关心处理的是单个的对象,还是组合的对象容器。

2)将“客户代码与复杂的对象容器结构”解耦是Composite模式的核心思想,解耦之后,客户代码将与纯粹的抽象接口——而非对象容器的复内部实现结构——发生依赖关系,从而更能“应对变化”。

3)Composite模式中,是将“Add和Remove等和对象容器相关的方法”定义在“表示抽象对象的Component类”中,还是将其定义在“表示对象容器的Composite类”中,是一个关乎“透明性”和“安全性”的两难问题,需要仔细权衡。这里有可能违背面向对象的“单一职责原则”,但是对于这种特殊结构,这又是必须付出的代价。ASP.NET控件的实现在这方面为我们提供了一个很好的示范。

4)Composite模式在具体实现中,可以让父对象中的子对象反向追溯;如果父对象有频繁的遍历需求,可使用缓存技巧来改善效率。

.NET框架中的Composite应用 ——ASP.NET控件结构分析

   public class _NetClass
{
public void Test()
{
Panel pnl = new Panel();
Button btn = new Button();

//Controls 是一个Control的集合,相当于上面IBox接口里面的一个属性。
//.Net 将所有控件都可以当做是容器。根据这个属性是否为null判断是不是包含子对象。
pnl.Controls.Add(btn);
}
}


推荐资源

1)《设计模式:可复用面向对象软件的基础》GoF

2)《面向对象分析与设计》Grady Booch

3)《敏捷软件开发:原则、模式与实践》Robert C. Martin

4)《重构:改善既有代码的设计》Martin Fowler

5)《Refactoring to Patterns》Joshua Kerievsky
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: