c#设计模式——组合模式

一 概要

1.1 结构型模式

  1. 关注类和对象的组合。继承的概念被用来组合接口和定义组合对象,从而获得新功能。

1.2 定义

  1. 有时又叫作部分-整体模式,它是一种将对象组合成树状的层次结构的模式,用来表示“部分-整体”的关系,使用户对单个对象和组合对象具有一致的访问性。

二 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 优点

  1. 灵活多样, 客户端可以根据自己的需求组合各个具体对象完成特定的功能。
  2. 相对继承来说, 耦合更低, 修改某个具体的组合对象的行为, 不会影响其他具体对象的行为。

4.2 缺点

  1. 使得设计更加复杂,客户端需要花更多时间理清类之间的层次关系。

五 使用场景

  1. 在需要表示一个对象整体与部分的层次结构的场合。
  2. 要求对用户隐藏组合对象与单个对象的不同,用户可以用统一的接口使用组合结构中的所有对象的场合。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值