Composite Pattern Example

A simple example of using the CompositePattern:

  // Copyright(C) 2000 Yoshinori Oota All rights reserved.

public class CompositeSample? { static public void main(String args[]) { /* [???] aComposite --aLeaf --aLeaf --Composite --aLeaf --aLeaf */ Component aComponent1 = new Composite(); Component aComponent2 = new Leaf(); Component aComponent3 = new Leaf(); aComponent1.AddComponent?(aComponent2); aComponent1.AddComponent?(aComponent3);

Component aComponent4 = new Composite(); Component aComponent5 = new Leaf(); Component aComponent6 = new Leaf(); aComponent4.AddComponent?(aComponent5); aComponent4.AddComponent?(aComponent6); aComponent1.AddComponent?(aComponent4);

// Opearation [???] aComponent1.Operation(); } }

abstract class Component { abstract public void Operation(); abstract public void AddComponent?(Component aComponent); }

class Leaf extends Component { public Leaf() { }

public void Operation() { System.out.println("**I'm Leaf"); }

public void AddComponent?(Component aComponent) { } }

class Composite extends Component { private Vector _components; //children

public Composite() { _components = new Vector(); }

public void Operation() { System.out.println("I'm Composite"); Enumeration componentList = _components.elements(); while(componentList.hasMoreElements()) { // forall Component in _components // aComponent.Operation();

Component aComponent = (Component)componentList.nextElement(); aComponent.Operation(); } }

public void AddComponent?(Component aComponent) { _components.addElement(aComponent); } }


Graphically:

Worth noting: This is not the GOF implementation, which puts the collection methods on the component. Heated discussion on CompositeConsideredHarmful.


EditText of this page (last edited April 25, 2006) or FindPage with title or text search