CS 635 Advanced Object-Oriented Design & Programming Spring Semester, 2002 Strategy |
||
---|---|---|
© 2002, All Rights Reserved, SDSU & Roger Whitney San Diego State University -- This page last updated 26-Feb-02 |
Strategy
Intent
Define a family of algorithms, encapsulate each one, and make them interchangeable
Strategy lets the algorithm vary independently from clients that use it
Structure
Examples
Java Layout Managers for Windows
Java Comparators
Smalltalk sort blocks
Java Layout Managers
import java.awt.*; class FlowExample extends Frame { public FlowExample( int width, int height ) { setTitle( "Flow Example" ); setSize( width, height ); setLayout( new FlowLayout( FlowLayout.LEFT) ); for ( int label = 1; label < 10; label++ ) add( new Button( String.valueOf( label ) ) ); show(); } public static void main( String args[] ) { new FlowExample( 175, 100 ); new FlowExample( 175, 100 ); } }
Why Not use Inheritance?
But there are:
Java Comparators
import java.util. Comparator; import java.util.*; class Student { String name; public Student( String newName) { name = newName;} public String toString() { return name; } } final class StudentNameComparator implements Comparator { public int compare( Object leftOp, Object rightOp ) { String leftName = ((Student) leftOp).name; String rightName = ((Student) rightOp).name; return leftName.compareTo( rightName ); } public boolean equals( Object comparator ) { return comparator instanceof StudentNameComparator; } } public class Test { public static void main(String args[]) { Student[] cs596 = { new Student( "Li" ), new Student( "Swen" ), new Student( "Chan" ) }; //Sort the array Arrays.sort( cs596, new StudentNameComparator() ); } }
Smalltalk SortBlocks
| list | list := #( 1 6 2 3 9 5 ) asSortedCollection. Transcript print: list; cr. list sortBlock: [:x :y | x > y]. Transcript print: list; cr; flush.
Why Not use Inheritance
There are arbitrarily many ways to sort
So get arbitrarily many
Applicability
Use the Strategy pattern when
Consequences
switch ( flag ) { case A: doA(); break; case B: doB(); break; case C: doC(); break; }
strategy.do();
SortedList studentRecords = new SortedList(new ShellSort());
Implementation
SortedList<ShellSort> studentRecords;