设计模式(结构型——Composite模式)

八、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();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值