八、Composite模式
8.1 Composite模式的概念
- 使用场景
- 针对容器类型的层次结构,使用Composite模式封装内部实现
- 例如,一个盒子,它内部还可以套一个盒子,直到盒子足够小,变成不可再分的单一对象,而不是再是容器对象。
- 客户端使用该类型时,通常会先判断该类型是单一对象还是容器对象,如果是容器对象,需要不断递归遍历容器。
8.2 Composite模式的实现
- 将遍历过程封装在类的内部,类的使用者不需要考虑类的具体类型是容器还是单一对象
- 为了达到这一目的,需要改造单一对象,使其具有容器类型的一些特征,这有违对象应该实现单一职责的原则
public interface IComponent
{
void Operation();
void Add(IComponent component);
void Remove(IComponent component);
}
public class Leaf : IComponent
{
public void Add(IComponent component)
{
throw new NotImplementedException();
}
public void Operation()
{
Console.WriteLine("处理叶子");
}
public void Remove(IComponent component)
{
throw new NotImplementedException();
}
}
public class Composite : IComponent
{
IList<IComponent> Components;
public void Add(IComponent component)
{
if (Components == null) Components = new List<IComponent>();
Components.Add(component);
}
public void Operation()
{
Console.WriteLine("处理Composite节点");
foreach (IComponent item in Components)
{
item.Operation();
}
}
public void Remove(IComponent component)
{
if (Components != null) Components.Remove(component);
}
}
class Program
{
static void Main(string[] args)
{
IComponent component = new Composite();
component.Add(new Leaf());
IComponent componentInside = new Composite();
componentInside.Add(new Leaf());
component.Add(componentInside);
component.Operation();
Console.ReadLine();
}
}