Sunday, August 17, 2014

Composite Pattern

Composite is about dealing the whole and the part in a uniform way. It's useful in building tree like structures and then working on them in a uniform way. Let's see how to implement one related to a tree.

The Node interface

public interface Node {
public void process();
}

The whole

public class NonLeafNode implements Node {
private final List<Node> nodeList = new ArrayList<Node>();

public void addNode(Node node) {
nodeList.add(node);

}

@Override
public void process() {
System.out.println("I am not a leaf node");
for (Node node : nodeList) {
node.process();
}
}
}

The part

public class Leaf implements Node {

@Override
public void process() {
System.out.println("I am leaf");
}
}

And the main method

public class Composite {

public static void main(String[] args) {
NonLeafNode root = new NonLeafNode();
NonLeafNode level1 = new NonLeafNode();
root.addNode(level1);

Leaf leaf = new Leaf();
level1.addNode(leaf);

root.process();
}

No comments:

Post a Comment