java设计模式之组合模式

组合模式

  组合模式,将对象组合成树形结构以表示“部分-整体”的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。掌握组合模式的重点是要理解清楚 “部分/整体” 还有 ”单个对象“ 与 “组合对象” 的含义。组合模式可以让客户端像修改配置文件一样简单的完成本来需要流程控制语句来完成的功能。经典案例:系统目录结构,网站导航结构等。(百度百科)

组合模式UML图

《java设计模式之组合模式》

组合模式代码

package com.roc.composite;
/**
 * 公共对象声明
 * @author liaowp
 *
 */
public abstract class Component {

    protected String name;
    
    public Component(String name){
        this.name=name;
    }
    
    public Component(){
    }
    
    public abstract void add(Component component);
    
    public abstract void remove(Component component);
    
    public abstract void display(int depth);

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
}
package com.roc.composite;

import java.util.ArrayList;
import java.util.List;

/**
 * 枝节点类
 * @author liaowp
 *
 */
public class ConcreteCompany extends Component{

    private List<Component> list;
    public ConcreteCompany(String name) {
        super(name);
        list=new ArrayList<Component>();
    }
    
    public ConcreteCompany(){
        list=new ArrayList<Component>();
    }

    @Override
    public void add(Component component) {
        list.add(component);
    }

    @Override
    public void remove(Component component) {
        list.remove(component);
    }

    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < depth; i++) {
            sb.append("-");
            }
            System.out.println(new String(sb) + this.getName());
            for (Component c : list) {
            c.display(depth + 2);
            }
    }
}
package com.roc.composite;
/**
 * 叶子节点
 * @author liaowp
 *
 */
public class Leaf extends Component{

    public Leaf(String name){
        super(name);
    }
    
    @Override
    public void add(Component component) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void remove(Component component) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void display(int depth) {
        StringBuilder sb = new StringBuilder("");
        for (int i = 0; i < depth; i++) {
            sb.append("-");
            }
            System.out.println(new String(sb) + this.getName());
    }

}
package com.roc.composite;
/**
 * 组合模式
 * @author liaowp
 *
 */
public class Client {
    public static void main(String[] args) {
        Component root=new ConcreteCompany("root");
        root.add(new Leaf("file A"));
        root.add(new Leaf("file B"));
        Component file=new ConcreteCompany("file1");
        file.add(new Leaf("file C"));
        file.add(new Leaf("file D"));
        root.add(file);
        root.display(1);
    }
}

组合模式适用场景 

  1.你想表示对象的部分-整体层次结构   2.你希望用户忽略组合对象与单个对象的不同,用户将统一地使用组合结构中的所有对象。

    原文作者:鹏&鹏
    原文地址: https://www.cnblogs.com/liaoweipeng/p/5791049.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞