组合模式(Composite)——Java

Component:节点的抽象类

public abstract class Component {

    public abstract void Operation();

    public abstract void Add(Component c);

    public abstract void Remove(Component c);

    public abstract Component GetChild(int i);

}


Composite:组合体,如树一般,可包含叶子节点或子树

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

public class Composite extends Component {

    // Composite由多个Component组成(聚合关系)
    private List list = new ArrayList();

    public void Operation() {
        for (Component c : list) {
            // 遍历所有子节点,并执行子节点的方法
            c.Operation();
        }
    }

    public void Add(Component c) {
        list.add(c);
    }

    @Override
    public void Remove(Component c) {
        // TODO Auto-generated method stub

    }

    @Override
    public Component GetChild(int i) {
        // TODO Auto-generated method stub
        return null;
    }

}


Leaf:叶子节点

public class Leaf extends Component {

    public void Operation() {
        System.out.println("this is leaf");
    }

    @Override
    public void Add(Component c) {
        // TODO Auto-generated method stub

    }

    @Override
    public void Remove(Component c) {
        // TODO Auto-generated method stub

    }

    @Override
    public Component GetChild(int i) {
        // TODO Auto-generated method stub
        return null;
    }

}


Client:客户端,构造一个组合体,并遍历该组合体的所有叶子节点,如下图所示:

组合模式(Composite)——Java_第1张图片



这个类很重要,这个类是否写正确,以及运行结果是否正确意味着对设计模式是否真正理解

public class Client {

    public static void main(String[] args) {
        Leaf leaf1 = new Leaf();// 叶子节点
        Leaf leaf2 = new Leaf();
        Leaf leaf3 = new Leaf();

        Composite c = new Composite();// 子树节点,包含两个叶子节点
        c.Add(leaf2);
        c.Add(leaf3);

        Composite composite = new Composite();// 树

        composite.Add(c);
        composite.Add(leaf1);

        composite.Operation();// 遍历所有节点
    }

}


你可能感兴趣的:(Design,Patterns)