Composite Pattern
Author: Deron Eriksson
Description: This Java tutorial describes the composite pattern, a structural design pattern.
Tutorial created using: Windows Vista || JDK 1.6.0_11 || Eclipse JEE Ganymede SR1 (Eclipse 3.4.1)


Page: < 1 2

(Continued from page 1)

The CompositeDemo class demonstrates the composite pattern. It creates 5 Leaf objects. It adds two of these two a Composite object and two of these to another Composite object. It adds these two Composite objects and the last Leaf object to another Composite object. It calls sayHello() on leaf1, then sayHello() on composite1, then sayHello() on composite2, and then sayGoodbye() on composite3.

CompositeDemo.java

package com.cakes;

public class CompositeDemo {

	public static void main(String[] args) {

		Leaf leaf1 = new Leaf("Bob");
		Leaf leaf2 = new Leaf("Fred");
		Leaf leaf3 = new Leaf("Sue");
		Leaf leaf4 = new Leaf("Ellen");
		Leaf leaf5 = new Leaf("Joe");

		Composite composite1 = new Composite();
		composite1.add(leaf1);
		composite1.add(leaf2);

		Composite composite2 = new Composite();
		composite2.add(leaf3);
		composite2.add(leaf4);

		Composite composite3 = new Composite();
		composite3.add(composite1);
		composite3.add(composite2);
		composite3.add(leaf5);

		System.out.println("Calling 'sayHello' on leaf1");
		leaf1.sayHello();

		System.out.println("\nCalling 'sayHello' on composite1");
		composite1.sayHello();

		System.out.println("\nCalling 'sayHello' on composite2");
		composite2.sayHello();

		System.out.println("\nCalling 'sayGoodbye' on composite3");
		composite3.sayGoodbye();

	}

}

The console output of executing CompositeDemo is shown here.

Console Output

Calling 'sayHello' on leaf1
Bob leaf says hello

Calling 'sayHello' on composite1
Bob leaf says hello
Fred leaf says hello

Calling 'sayHello' on composite2
Sue leaf says hello
Ellen leaf says hello

Calling 'sayGoodbye' on composite3
Bob leaf says goodbye
Fred leaf says goodbye
Sue leaf says goodbye
Ellen leaf says goodbye
Joe leaf says goodbye

As seen in the output, the composite pattern allows us to perform operations on the composites and leaves that make up a tree structure via a common interface.

Page: < 1 2


Related Tutorials: