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;  
        }  
    }  
  • 相关阅读:
    Python 写一个俄罗斯方块游戏
    您能解决这3个(看似)简单的Python问题吗?
    Python selenium爬虫实现定时任务过程解析
    Python-Django-Ajax进阶2
    Python-Django-Ajax进阶
    Python 数据-入门到进阶开发之路
    Python-Numpy数组计算
    Python-Django-Ajax
    Python-web应用 +HTTP协议 +web框架
    Python-socketserver实现并发- 源码分析
  • 原文地址:https://www.cnblogs.com/guwei4037/p/6689376.html
Copyright © 2011-2022 走看看