Composite组合模式属于结构型设计模式,将对象组合成树结构以表示部分-整体层次结构,Composite 让客户可以统一地对待单个对象和对象的组合。
Design Pattern:Composite 🔗
基本介绍 🔗
构成 🔗
- Component:抽象组件类,为层次结构中的所有对象定义公共的接口及默认行为。
- Leaf:树叶类,树叶类是没有下级子对象的对象,定义了组合中原始对象的行为。
- Composite:树枝类,树枝类是拥有下级子对象组合的对象,定义了可以对子对象组合执行的必要操作。
- Client:客户使用类,通过Component接口操作组合中对象的类。
优点 🔗
- 有助于在包含原始对象类型和复合对象类型的对象层次结构中实现统一性。
- 遵循开放/封闭原则,可以在不更改现有代码的情况下添加更多组件。
缺点 🔗
- 由于其统一性,复合模式有时会变得过于笼统,有时很难为具有许多不同功能的类定义标准接口。
实例 🔗
C#中组合模式的实例,下面我们来到电子城,根据自己的需求组装一台电脑。
public interface IComponent
{
/// <summary>
/// 显示价格
/// </summary>
void DisplayPrice();
}
/// <summary>
/// 树叶类
/// </summary>
public sealed class Leaf : IComponent
{
/// <summary>
/// 组件名字
/// </summary>
private string _componentName;
/// <summary>
/// 组件价格
/// </summary>
private int _componentPrice;
public Leaf(string name, int price)
{
_componentName = name;
_componentPrice = price;
}
public void DisplayPrice()
{
Console.WriteLine($"\tComponent Name: {_componentName} and Price: {_componentPrice}");
}
}
/// <summary>
/// 树枝类
/// </summary>
public sealed class Composite : IComponent
{
/// <summary>
/// 组件名字
/// </summary>
private string _componentName;
/// <summary>
/// 子组件
/// </summary>
private List<IComponent> _components = new List<IComponent>();
public Composite(string name)
{
_componentName = name;
}
/// <summary>
/// 添加组件
/// </summary>
/// <param name="component"></param>
public void AddComposite(IComponent component)
{
_components.Add(component);
}
public void DisplayPrice()
{
foreach (var component in _components)
component.DisplayPrice();
}
}
实际运行:
//CPU
IComponent cpu = new Leaf("CPU", 2000);
//鼠标
IComponent mouse = new Leaf("Mouse", 2000);
//键盘
IComponent keyboard = new Leaf("Keyboard", 2000);
//输入设备
Composite inputEquipment = new Composite("InputEquipment");
inputEquipment.AddComposite(mouse);
inputEquipment.AddComposite(keyboard);
//电脑
Composite computer = new Composite("Computer");
computer.AddComposite(cpu);
computer.AddComposite(inputEquipment);
//显示设备价格
computer.DisplayPrice();
结论 🔗
搬砖愉快!