首页 > 其他分享 >组合模式

组合模式

时间:2023-06-03 21:46:17浏览次数:35  
标签:组合 Composite component 模式 class IComponent objects public

The Composite design pattern composes objects into tree structures to represent part-whole hierarchies. This pattern lets clients treat individual object and compositions of objects uniformly.

组合模式将对象组合成tree结构代表部分-整体层次结构,这种模式允许客户端统一处理单个对象和组合对象。

UML Class Disgram 

 Component: This is going to be an abstract or interface containing the members that will be implemented by both Leaf and Composite Classess. If required then it can also implement some of behavior that is common to all objects in the composition and in that case we need to create the Component as an abstract class.That means the abstract class or interface acts as the base class for all the objects within the hierarchiy.

  Leaf: This is going to be a class to present the leaf behavior in the composition.

  Composite: The Composite defines the behavior of the Composite Components. THe Composite have children. The chidlren can be another composite component or can be a leaf component.

   Client: The Client is the class that manipulates objects in the composition through the Component interface. 

 

    /// <summary>
    /// The base Component class declares the common operations for both simple and complex objects.
    /// </summary>
    public interface IComponent
    {
        void Add(IComponent component);
        void Remove(IComponent component);
        void Display(int depth);
    }
Component
 /// <summary>
    /// The Compoiste class represents the complex component that have children.
    /// The Composite objects delegate the actual work to their children and the combine the result.
    /// </summary>
    public class Composite : IComponent
    {
        public List<IComponent> children = new List<IComponent>();
        public string Name;
        public Composite(string name)
        {
            this.Name = name;
        }

        public void Add(IComponent component)
        {
            children.Add(component);
        }

        public void Remove(IComponent component)
        {
            children.Remove(component);
        }

        public void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + Name);
            foreach (var component in children)
            {
                component.Display(depth + 2);
            }
        }
    }
Composite
  /// <summary>
    /// The Leaf class represents the end objects.
    /// A leaf can't have any children.
    /// The leaf object is the object which does the actual work.
    /// </summary>
    public class Leaf : IComponent
    {
        public string Name;
        public Leaf(string name)
        {
            this.Name = name;
        }
        public void Add(IComponent component)
        {
            Console.WriteLine("Cannot add to a leaf");
        }

        public void Remove(IComponent component)
        {
            Console.WriteLine("Cannot remove from a leaf.");
        }

        public void Display(int depth)
        {
            Console.WriteLine(new string('-', depth) + Name);
        }
    }
Leaf

When do we need to use the Composite Desgin Pattern in C#?

  • we want to represent part-whole hierarchies of objects.
  • we want to the client ignore the difference between the compositions of objects and individual objects.

标签:组合,Composite,component,模式,class,IComponent,objects,public
From: https://www.cnblogs.com/qindy/p/17409387.html

相关文章

  • 装饰器模式
    TheDecoratorDesignPatternattachesadditionalresponsibilitiestoanobjectdynamically.Thispatternprovideaflexiblealternativetosubclassingforextendingfunctionality.装饰器模式动态的给Object添加额外的职责,这个模式为SubClassing提供灵活的扩展功能。......
  • 外观模式
    TheFacade designpattenprovidesaunifiedinterfacetoasetofinterfacesinasubsystem.Thispatterndefinesahigher-levelinterfacethatmakesthesubsystemeasiertouse.外观模式为子系统一组接口提供了统一的接口,这种模式定义了高级接口,便于子系统调用。......
  • 适配器模式
    TheAdpativedesignpatternconvertstheinterfaceofaclasstoanotherinterfaceclientsexpect.Thisdesignpatternletsclassesworktogetherthatcouldn'totherwisebecauseofincompatibleinterfaces.适配器模式将类的接口转换为客户期望的另外一个接口,这种......
  • 桥接模式
    TheBridgedesignpatterndecouplesanabstractionfromitsimplementationsothathetwocanvaryindependently.桥接模式将抽象和实现解耦,以便两者可以独立变化。UMLClassDiagram Abstraction:definestheabstraction'sinterface;matainsareferencetoanobj......
  • 模板方法模式
    TheTemplateMethoddesignpatterndefinestheskeletonofanalgorithminanoperation,deferingsomestepstosubclasses.Thispatternletssubclassesredefinecertainstepsofanalgorithmwihoutchangingthealgorithm'sstructure.模板方法设计模式在操作中......
  • 创建型设计模式
    TheCreationalDesignPatternareCategorizedintotwotypes. Object-CreationalPatterns:Object-CreationalPatternsdealwithobjectcreation.Here,itdeferspartofitsobjectcreationtoanotherobject.Class-CreationalPatterns:Class-CreationalPa......
  • 策略模式
    TheStrategydesignpatterndefinesafamiliyofalgorithms,encapsulateeachone,andmaketheminterchangeable.Thispatternletsthealgorithmvaryindependentlyfromclientthatuseit.策略模式定义一系列算法,封装它,使他们可以互换,这种设计模式使算法独立于客......
  • 3月25日邓老师设计模式面试资料02
    Spring面试专题1.Spring应该很熟悉吧?来介绍下你的Spring的理解  有些同学可能会抢答,不熟悉!!!  好了,不开玩笑,面对这个问题我们应该怎么来回答呢?我们给大家梳理这个几个维度来回答1.1Spring的发展历程  先介绍Spring是怎么来的,发展中有哪些核心的节点,当前的最新版本是......
  • 大话设计模式之单例,策略,简单工厂
    基于实际面试题实现importjava.util.HashMap;importjava.util.Map;importjava.util.Random;/***用java设计一个机房环境监测系统的代码框架,机房有多种传感器,可以实时检测机房的温度、湿度、噪音等数据,*并把数据实时发送到监控中心,其中某项数据超过不健康阈值立即上......
  • 树莓派如果通过 raspi-config 关闭桌面模式 All In One
    树莓派如果通过raspi-config关闭桌面模式AllInOne树莓派设置启动模式:切换桌面模式和命令行模式DesktopCommandLineGUIvsCLI图形化界面vs命令行$sudoraspi-config$sudovim/boot/config.txt$sudoreboot$sudoshutdwon-hnowautologinde......