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) {


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

The part

public class Leaf implements Node {

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();

Leaf leaf = new Leaf();


No comments:

Post a Comment