Loading

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;  
    }  
}  

 

posted @ 2017-04-10 15:47  guwei4037  阅读(238)  评论(0编辑  收藏  举报