组合模式-Composite

名称:

    组合模式(Composite Pattern)-对象结构型模式

 

问题:

    Compose Objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly。

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

 

适用性:

    -你想表示对象的部分-整体层次结构。

    -你希望用户忽略组合对象与单个对象的不同、用户将统一的使用组合结构中的所有对象。

 

协作:

    用户使用Component类接口与组合结构中的对象进行交互。如果接受者是一个叶节点,则直接处理请求。如果接受者是Composite,它通常将请求发送给它的子部件,在转发之前与/或之后可能执行一些辅助操作。

 

优点和缺点:

    1、定义了包含基本对象和组合对象的类层次结构。

    2、简化客户代码。

    3、使得更容易增加新类型的组件。

    4、使你的设计变得更加一般化。

解决方案:

    

1、 模式的参与者

    1、Component

    -为组合中的对象声明接口。

    -在适当的情况下,实现所有类共有接口的缺省行为。

    -声明一个接口用于访问和管理Component的子组件。

    -(可选)在递归结构中定义一个接口,用于访问一个父部件,并在合适的情况下实现它。

    2、Leaf

    -在组合中表示叶节点对象,叶节点没有子节点。

    -在组合中定义图元对象的行为。

    3、Composite

    -定义有子部件的那些部件的行为。

    -存储子部件。

    -在Component接口中实现与子部件有关的操作。

    4、Client

    -通过Component接口操纵组合部件的对象。

2.实现方式

interface Component
{
    public void add(Component c);
    public void remove(Component c);
    public Component getChild(int i);
    public void operation();
}
class Leaf implements Component
{
    private String name;
    public Leaf(String name)
    {
        this.name=name;
    }
    public void add(Component c){ }           
    public void remove(Component c){ }   
    public Component getChild(int i)
    {
        return null;
    }   
    public void operation()
    {
        System.out.println("leaf:"+name); 
    }
}
class Composite implements Component
{
    private ArrayList<Component> children=new ArrayList<Component>();   
    public void add(Component c)
    {
        children.add(c);
    }   
    public void remove(Component c)
    {
        children.remove(c);
    }   
    public Component getChild(int i)
    {
        return children.get(i);
    }   
    public void operation()
    {
        for(Object obj:children)
        {
            ((Component)obj).operation();
        }
    }    
}
public class CompositePattern
{
    public static void main(String[] args)
    {
        Component c0=new Composite(); 
        Component c1=new Composite(); 
        Component leaf1=new Leaf("1"); 
        Component leaf2=new Leaf("2"); 
        Component leaf3=new Leaf("3");          
        c0.add(leaf1); 
        c0.add(c1);
        c1.add(leaf2); 
        c1.add(leaf3);          
        c0.operation(); 
    }
}

 

参考资料

《设计模式:可复用面向对象软件的基础》

posted @ 2020-06-26 19:52  diameter  阅读(121)  评论(0编辑  收藏  举报