前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >组合模式(Composite)

组合模式(Composite)

作者头像
兜兜转转
发布2023-03-06 15:16:31
2540
发布2023-03-06 15:16:31
举报
文章被收录于专栏:CodeTime

意图

组合模式是一种结构型模式,你可以使用它将对象组合成树状结构,并且能像使用独立对象一样使用它们。

问题

如果应用的核心模型能用树状结构表示,在应用中使用组合模式才有价值。

例如,你有两类对象:产品盒子。一个盒子中可以包含多个产品或者几个较小的盒子。这些小盒子中同样可以包含一些产品或更小的盒子,以此类推。

假设你希望在这些类的基础上开发一个定购系统。订单中可以包含无包装的简单产品,也可以包含装满产品的盒子……以及其他盒子。此时你会如何计算每张订单的总价格呢?

订单中可能包括各种产品,这些产品放置在盒子中,然后又被放入一层又一层更大的盒子中。整个结构看上去像是一棵倒过来的树
订单中可能包括各种产品,这些产品放置在盒子中,然后又被放入一层又一层更大的盒子中。整个结构看上去像是一棵倒过来的树

你可以尝试直接计算:打开所有盒子,找到每件产品,然后计算总价。这在真实世界中或许可行,但在程序中,你并不能简单地使用循环语句来完成该工作。你必须事先知道所有产品盒子的类别,所有盒子的嵌套层数以及其他繁杂的细节信息。因此,直接计算极不方便,甚至完全不可行。

解决方案

组合模式建议使用一个通用接口来与产品盒子进行交互,并且在该接口中声明一个计算总价的方法。

那么方法该如何设计呢?对于一个产品,该方法直接返回其价格;对于一个盒子,该方法遍历盒子中的所有项目,询问每个项目的价格,然后返回该盒子的总价格。如果其中某个项目是小一号的盒子,那么当前盒子也会遍历其中的所有项目,以此类推,直到计算出所有内部组成部分的价格。你甚至可以在盒子的最终价格中增加额外费用,作为该盒子的包装费用。

组合模式以递归方式处理对象树中的所有项目
组合模式以递归方式处理对象树中的所有项目

该方式的最大优点在于你无需了解构成树状结构的对象的具体类。你也无需了解对象是简单的产品还是复杂的盒子。你只需调用通用接口以相同的方式对其进行处理即可。当你调用该方法后,对象会将请求沿着树结构传递下去。

结构

  1. 组件(Component)接口描述了树中简单项目和复杂项目所共有的操作。
  2. 叶节点(Leaf)是树的基本结构,它不包含子项目。 一般情况下,叶节点最终会完成大部分的实际工作,因为它们无法将工作指派给其他部分。
  3. 容器(Container)——又名“组合(Composite)”——是包含叶节点或其他容器等子项目的单位。容器不知道其子项目所属的具体类,它只通过通用的组件接口与其子项目交互。 容器接收到请求后会将工作分配给自己的子项目,处理中间结果,然后将最终结果返回给客户端。
  4. 客户端(Client)通过组件接口与所有项目交互。因此,客户端能以相同方式与树状结构中的简单或复杂项目交互。

实现方式

  1. 确保应用的核心模型能够以树状结构表示。尝试将其分解为简单元素和容器。记住,容器必须能够同时包含简单元素和其他容器。
  2. 声明组件接口及其一系列方法,这些方法对简单和复杂元素都有意义。
  3. 创建一个叶节点类表示简单元素。程序中可以有多个不同的叶节点类。
  4. 创建一个容器类表示复杂元素。在该类中,创建一个数组成员变量来存储对于其子元素的引用。该数组必须能够同时保存叶节点和容器,因此请确保将其声明为组合接口类型。 实现组件接口方法时,记住容器应该将大部分工作交给其子元素来完成。
  5. 最后,在容器中定义添加和删除子元素的方法。 记住,这些操作可在组件接口中声明。这将会违反接口隔离原则,因为叶节点类中的这些方法为空。但是,这可以让客户端无差别地访问所有元素,即使是组成树状结构的元素。

代码演示

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151

using System;using System.Collections.Generic;namespace RefactoringGuru.DesignPatterns.Composite.Conceptual{ // The base Component class declares common operations for both simple and // complex objects of a composition. abstract class Component { public Component() { } // The base Component may implement some default behavior or leave it to // concrete classes (by declaring the method containing the behavior as // "abstract"). public abstract string Operation(); // In some cases, it would be beneficial to define the child-management // operations right in the base Component class. This way, you won't // need to expose any concrete component classes to the client code, // even during the object tree assembly. The downside is that these // methods will be empty for the leaf-level components. public virtual void Add(Component component) { throw new NotImplementedException(); } public virtual void Remove(Component component) { throw new NotImplementedException(); } // You can provide a method that lets the client code figure out whether // a component can bear children. public virtual bool IsComposite() { return true; } } // The Leaf class represents the end objects of a composition. A leaf can't // have any children. // // Usually, it's the Leaf objects that do the actual work, whereas Composite // objects only delegate to their sub-components. class Leaf : Component { public override string Operation() { return "Leaf"; } public override bool IsComposite() { return false; } } // The Composite class represents the complex components that may have // children. Usually, the Composite objects delegate the actual work to // their children and then "sum-up" the result. class Composite : Component { protected List<Component> _children = new List<Component>(); public override void Add(Component component) { this._children.Add(component); } public override void Remove(Component component) { this._children.Remove(component); } // The Composite executes its primary logic in a particular way. It // traverses recursively through all its children, collecting and // summing their results. Since the composite's children pass these // calls to their children and so forth, the whole object tree is // traversed as a result. public override string Operation() { int i = 0; string result = "Branch("; foreach (Component component in this._children) { result += component.Operation(); if (i != this._children.Count - 1) { result += "+"; } i++; } return result + ")"; } } class Client { // The client code works with all of the components via the base // interface. public void ClientCode(Component leaf) { Console.WriteLine($"RESULT: {leaf.Operation()}\n"); } // Thanks to the fact that the child-management operations are declared // in the base Component class, the client code can work with any // component, simple or complex, without depending on their concrete // classes. public void ClientCode2(Component component1, Component component2) { if (component1.IsComposite()) { component1.Add(component2); } Console.WriteLine($"RESULT: {component1.Operation()}"); } } class Program { static void Main(string[] args) { Client client = new Client(); // This way the client code can support the simple leaf // components... Leaf leaf = new Leaf(); Console.WriteLine("Client: I get a simple component:"); client.ClientCode(leaf); // ...as well as the complex composites. Composite tree = new Composite(); Composite branch1 = new Composite(); branch1.Add(new Leaf()); branch1.Add(new Leaf()); Composite branch2 = new Composite(); branch2.Add(new Leaf()); tree.Add(branch1); tree.Add(branch2); Console.WriteLine("Client: Now I've got a composite tree:"); client.ClientCode(tree); Console.Write("Client: I don't need to check the components classes even when managing the tree:\n"); client.ClientCode2(tree, leaf); } }}

执行结果:

12345678

Client: I get a simple component:RESULT: LeafClient: Now I've got a composite tree:RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf))Client: I don't need to check the components classes even when managing the tree:RESULT: Branch(Branch(Leaf+Leaf)+Branch(Leaf)+Leaf)

参考原文:组合设计模式

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021-06-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 意图
  • 问题
  • 解决方案
  • 结构
  • 实现方式
  • 代码演示
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档