Lecture14 - Example The Composite composes objects into tree structures and lets clients treat individual objects and compositions uniformly 1 Ensure

Lecture14 - Example The Composite composes objects into...

This preview shows page 1 - 9 out of 28 pages.

Example The Composite composes objects into tree structures and lets clients treat individual objects and compositions uniformly. 1. Ensure that your problem is about representing "whole-part" hierarchical relationships. We want to perform the same operation on composite and leaf obje ct 2. Component contains leaf and component. Divide your domain concepts into component class, and leaf classes. 3. Create a interface that specify the behavior that needs to be exercised uniformly across all component and leaf objects. 1
Image of page 1
interface AbstractFile { public void ls();} // ***** File implements the interface" class File implements AbstractFile { private String m_name; public File( String name ) { m_name = name; } public void ls() { System.out.println(m_name ); } } // ***** Directory implements the interface" class Directory implements AbstractFile { private String m_name; private ArrayList m_files = new ArrayList(); public Directory( String name ) { m_name = name; } public void add( Object obj ) { m_files.add( obj ); } 2
Image of page 2
public void ls() { for (int i=0; i < m_files.size(); ++i) { // ***** Leverage the "interface" AbstractFile obj = (AbstractFile) m_files.get(i); obj.ls(); } } } public class CompositeDemo { public static void main( String[] args ) { Directory one = new Directory("dir111"), two = new Directory("dir222"), thr = new Directory("dir333"); a c d e b File a = new File("a"), b = new File("b"), c = new File("c"), d = new File("d"), e = new File("e"); one.add( a ); one.add( two ); one.add( b ); two.add( c ); two.add( d ); two.add( thr ); thr.add( e ); one.ls(); } } 3
Image of page 3
The State Pattern Intention Allows an object to alter its behavior when its internal state changes. The state of objects? The particular values of the instance variables affect the object's behavior. Class Sun() { String Color; public boolean sunIsVisible(){ if(Color== “blue”) { return true; } else { return false; } } 4
Image of page 4
increaseTemp() decreaseTemp() WaterVapor increaseTemp() decreaseTemp() Ice increaseTemp() decreaseTemp() LiquidWater increaseTemp() decreaseTemp() Client increaseTemp() water increaseTemp() decreaseTemp() state variable StateOfWater 5
Image of page 5
6
Image of page 6
Hash(x) = x mod 8 null null null null Obj5 key=1 obj1 key=15 Obj4 key=2 Obj2 key=28 Obj3 key=4 7 6 5 4 3 2 1 0 7
Image of page 7
Image of page 8
Image of page 9

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture