第十九章 组合模式

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

希望用户可以忽略组合对象与单个对象的不同,统一的使用组合结构中的所有对象时,就应该考虑使用组合模式。

//我没写过OA系统,不能理解组合模式。

/**
 * Created by hero on 16-4-6.
 */
public abstract class Component {
    protected String name;

    public abstract void add(Component component);

    public abstract void remove(Component component);

    public abstract void display(int depth);

    public Component(String name) {
        this.name = name;
    }
}
/**
 * Created by hero on 16-4-6.
 */
public class Leaf extends Component {
    @Override
    public void add(Component component) {

    }

    @Override
    public void remove(Component component) {

    }

    @Override
    public void display(int depth) {
        CharUtils.print('-', depth);
        System.out.println(name);
    }

    public Leaf(String name) {
        super(name);
    }
}
import java.util.LinkedList;
import java.util.List;

/**
 * Created by hero on 16-4-6.
 */
public class Composite extends Component {

    private List<Component> children = new LinkedList<>();

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

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

    @Override
    public void display(int depth) {
        CharUtils.print('-', depth);
        System.out.println(name);
        for (Component component : children) {
            component.display(depth + 2);
        }
    }

    public Composite(String name) {
        super(name);
    }
}
/**
 * Created by hero on 16-4-6.
 */
public class CharUtils {
    public static void print(char c, int t) {
        for (int i = 0; i < t; i++)
            System.out.print(c);
    }
}
public class Main {

    public static void main(String[] args) {
        Composite root = new Composite("root");
        root.add(new Leaf("leaf A"));
        root.add(new Leaf("leaf B"));

        Composite comp1 = new Composite("comp1");
        comp1.add(new Leaf("leaf XA"));

        root.add(comp1);

        root.display(1);
    }
}
原文地址:https://www.cnblogs.com/littlehoom/p/5361300.html