天天看點

設計模式之組合模式

組合模式

組合模式分為安全組合模式和透明組合模式,本文下的示例代碼為透明組合模式,在葉子節點中備援實作了葉子節點不需要的方法,而安全組合模式則需要進行葉子節點和普通節點的區分.

  1. 組合模式結構圖
    設計模式之組合模式
  2. 示例代碼
// 抽象類
public abstract class Component {

    protected String name;

    public Component(String name) {
        this.name = name;
    }

    public abstract void add(Component component);

    public abstract void remove(Component component);

    public abstract void display(int depth);
}

// 葉子節點
public class Leaf extends Component{

    public Leaf(String name) {
        super(name);
    }

    @Override
    public void add(Component component) {

    }

    @Override
    public void remove(Component component) {

    }

    @Override
    public void display(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("-");
        }
        System.out.println(name);
    }
}

// 普通節點
public class Composite extends Component{

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

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

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

    @Override
    public void display(int depth) {
        for (int i = 0; i < depth; i++) {
            System.out.print("-");
        }
        System.out.println(name);
        for (Component component : list) {
            component.display(depth + 2);
        }
    }
}

// 測試
public class CompositeTest {

    public static void main(String[] args) {
        Component root = new Composite("root");
        Component branch1 = new Composite("branch1");
        Component branch2 = new Composite("branch2");
        Component leaf1 = new Composite("leaf1");
        Component branch11 = new Composite("branch11");
        Component branch12 = new Composite("branch12");
        Component branch13 = new Composite("branch13");
        Component leaf21 = new Composite("leaf21");
        Component leaf121 = new Composite("leaf121");
        root.add(branch1);
        root.add(branch2);
        root.add(leaf1);
        branch1.add(branch11);
        branch1.add(branch12);
        branch1.add(branch13);
        branch12.add(leaf121);
        branch2.add(leaf21);

        root.display(2);
    }
}

           
  1. 總結:

    優點:清楚的定義了各層次的複雜對象,符合開閉原則;

    缺點:限制類型時會較為複雜,使設計變得更加抽象.