组合模式

转载请注明出处!

http://blog.csdn.net/zhonghuan1992

         全部配套代码均在github上:https://github.com/ZHONGHuanGit/DesignPattern




跟着ZHONGHuan学习设计模式

组合模式







介绍:

         想必你已经了解了数据结构中的树,ok,组合模式对于你就是一会儿的功夫了。组合模式相对来说比較简单。

看一下定义

         组合模式将对象组合成树形结构以表示“部分-总体”的层次结构。使得用户对单个对象和组合对象的使用具有一致性。

        

         临时没有想到好的样例。假设你有,请告诉我。以下我用树来对组合模式进行解释。树的结构是以下的这种:

        

         没棵树有一个根节点,也有叶子节点和树枝节点。一些结构都是用树结构表示的。比如树形菜单,文件和文件夹文件夹。那么怎样存储管理这种树结构,能够组合模式来解决。

组合模式的类图

        

         组合模式比較简单。所以。通过以下的代码,应该就能了解组合模式的含义了。

 

import java.util.ArrayList;

abstract class Component
{
    protected String name; //这个用来标示一下节点
    public Component(String name)
    {
        this.name = name;
    }
 
    public abstract void add(Component c);//添加儿子节点
    public abstract void remove(Component c);//删除儿子节点
}

class Leaf extends Component
{
    public Leaf(String name)
    {
       super(name);
    }
 
    public  void add(Component c)
    {
       System.out.println("叶子节点不能添加子节点");
    }
 
    public void remove(Component c)
    {
    	System.out.println("叶子节点没有子节点,移除神马");
    }
}

class Composite extends Component
{
 
    ArrayList<Component> child;
 
    public Composite(String name)
    {
    	super(name);
        if (child == null)
        {
            child = new ArrayList<Component>();
        }
    }
 
    public void add(Component c)
    {
        this.child.add(c);
    }
 
    public void remove(Component c)
    {
        this.child.remove(c);
    }
}

public class Client{
	public static void main(String[] args)
	{
		Component tree=new Composite("A");//根节点通常是composite节点,给根节点取名A
		Component leafB=new Leaf("B");//创建了一个叶子节点B
		tree.add(leafB);//根节点有一个叶子节点儿子
		
		Component branchC=new Composite("C");//一个树枝节点C
		tree.add(branchC);//树枝节点C是根节点A的子节点
		
		Component leafD = new Leaf("D");
		branchC.add(leafD);//树枝节点C有一个叶子子节点D
		
		//树结构大致构造完成
	}
}


         组合模式让我们能用树形方式创建对象的结构。树里面包括了组合以及个别的对象。使用组合结构。我们能把同样的操作应用在组合和个别对象上。换句话说。在大多数情况下,我们能够忽略对象组合和个别对象之间的区别。

原文地址:https://www.cnblogs.com/mengfanrong/p/5243168.html