一 概要
1.1 结构型模式
- 关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。
1.2 定义
- 有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。
二 UML类图
三 例子
class Program
{
static void Main(string[] args)
{
ComponentB componentB = new ComponentB();
componentB.Add(new ComponentA());
ComponentB component = new ComponentB();
component.Add(componentB);
}
}
public interface Component
{
void Add(Component component);
void Remove(Component component);
}
public class ComponentA : Component
{
private string state;
public void Add(Component component)
{
}
public void Remove(Component component)
{
}
}
public class ComponentB : Component
{
private List<Component> components = new List<Component>();
public void Add(Component component)
{
components.Add(component);
}
public void Remove(Component component)
{
components.Add(component);
}
}
四 优缺点
4.1 优点
- 灵活多样, 客户端可以根据自己的需求组合各个具体对象完成特定的功能。
- 相对继承来说, 耦合更低, 修改某个具体的组合对象的行为, 不会影响其他具体对象的行为。
4.2 缺点
- 使得设计更加复杂,客户端需要花更多时间理清类之间的层次关系。
五 使用场景
- 在需要表示一个对象整体与部分的层次结构的场合。
- 要求对用户隐藏组合对象与单个对象的不同,用户可以用统一的接口使用组合结构中的所有对象的场合。