初尝Composite 设计模式
好久没有更新学习笔记了。对于这个设计模式,准确的说,我学习了2.5 遍。并非这个模式有多么Composite ,反倒是自己的生活安排上出现了很多很Composite 的故事。话不多说,开始正题。
我们的生活中,有很多和套娃类似的事务,一层套一层,一环扣一环,以至于使得人们晕头转向。在OO的世界里,面临着同样的问题,也需要解决这样的复合问题。最常见的,是数学表达式:一个操作符的两边,可以是2个操作数,这其中的一个操作数本身就可能是另一个表达式,表达式又蕴藏着前面提到的操作符、操作数和表达式之间的关系,有限的嵌套循环下去。(如:2+3*4,加号两边分别是一个操作数2和另一个表达式3*4)。
概述
组合模式有时候又叫做部分-整体模式,它使我们树型结构的问题中,模糊了简单元素和复杂元素的概念,客户程序可以向处理简单元素一样来处理复杂元素,从而使得客户程序与复杂元素的内部结构解耦。
意图
将对象组合成树形结构以表示“部分-整体”的层次结构。Composite模式使得用户对单个对象和组合对象的使用具有一致性。
一段代码
using System;
using System.Collections;
namespace Composite
{
public interface IBox
{
void Process();
void Add(IBox box);
void Remove(IBox box);
}
public class SingleBox : IBox
{
private string name;
public SingleBox(string name)
{
this.name = name;
}
public void Process()
{
Console.WriteLine("Process in the {0} SingleBox",name);
}
public void Add(IBox box)
{
throw new Exception();
}
public void Remove(IBox box)
{
throw new Exception();
}
}
public class ContainerBox : IBox
{
ArrayList list;
string name;
public ContainerBox(string name)
{
this.name = name;
}
public void Add(IBox box)
{
if (list == null)
list = new ArrayList();
list.Add(box);
}
public void Remove(IBox box)
{
if (list == null)
list = new ArrayList();
list.Remove(box);
}
public void Process()
{
//迭代的过程,使得复合类型和简单类型的操作一致
Console.WriteLine("Process in the {0} ContainerBox", name);
foreach (IBox box in list)
{
box.Process();
}
}
}
class Program
{
static void Main(string[] args)
{
ContainerBox cb = new ContainerBox("cb1st");
SingleBox sb = new SingleBox("1st");
cb.Add(sb);
ContainerBox cb2 = new ContainerBox("cb2nd");
cb2.Add(cb);
cb2.Process();
}
}
}


近期评论