zoukankan      html  css  js  c++  java
  • 23种设计模式之组合模式(Composite)

    组合模式又称为整体-部分(Part-whole)模式,属于对象的结构模式。在组合模式中,通过组合多个对象形成树形结构以表示整体-部分的结构层次。组合模式对单个对象(即叶子对象)和组合对象(即容器对象)的使用具有一致性。

    优点:

    1)定义了由主要对象和复合对象组成的类层次结构

    2)使得添加新的组件类型更加简单。

    3)提供了结构的灵活性和可管理的接口。

    使用场景:

    1)想要表示对象的整个或者部分的层次结构。

    2)想要客户端能够忽略复合对象和单个对象之间的差异。

    3)结构可以具有任何级别的复杂性,而且是动态的。

     

    Composite 模式

    public class File : AbstractFile  
    {  
        public File(string name)  
        {  
            this.name = name;  
        }  
      
        public override bool AddChild(AbstractFile file)  
        {  
            return false;  
        }  
      
        public override bool RemoveChild(AbstractFile file)  
        {  
            return false;  
        }  
      
        public override IList<AbstractFile> GetChildren()  
        {  
            return null;  
        }  
    }  
    public abstract class AbstractFile  
    {  
        protected string name;  
        public void PrintName()  
        {  
            Console.WriteLine(name);  
        }  
      
        public abstract bool AddChild(AbstractFile file);  
        public abstract bool RemoveChild(AbstractFile file);  
        public abstract IList<AbstractFile> GetChildren();  
    }  
    public class Folder : AbstractFile  
    {  
        private IList<AbstractFile> childList;  
        public Folder(string name)  
        {  
            this.name = name;  
            this.childList = new List<AbstractFile>();  
        }  
      
        public override bool AddChild(AbstractFile file)  
        {  
            childList.Add(file);  
            return true;  
        }  
      
        public override bool RemoveChild(AbstractFile file)  
        {  
            childList.Remove(file);  
            return true;  
        }  
      
        public override IList<AbstractFile> GetChildren()  
        {  
            return childList;  
        }  
    }  
  • 相关阅读:
    BiLiBiLi爬虫
    12-UE4-控件类型
    11-UE4-UMG UI设计器
    10-UE4-蓝图定义简介
    UE4-目录结构简介
    UE4-字符串
    UE4-基类
    Redis-事物
    Redis的主从配置
    Redis持久化-AOF
  • 原文地址:https://www.cnblogs.com/guwei4037/p/6689376.html
Copyright © 2011-2022 走看看