Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes
Strategy Pattern This is a set of slides to accompany chapter 8 of Mark Grand’s book Patterns in Java : a catalog of reusable design patterns illustrated with UML (John Wiley & Sons, 1998) Created: 19 August 2004 Revised: 20 April 2010
Context Any one of a family of algorithms may do a task Wish to make then dynamically interchangeable Invoke only operations on the base class Delegate creation of the actual subclass object to a special class – factory 1
General Approach Common interface to family abstract class/interface Encapsulate algorithm into implementing (sub)class Encapsulate algorithm into implementing (sub)class Delegate task by using interface 2
Example CalendarDisplay uses a Holiday instance to determine what holidays fall on each date Actually use instance of an appropriate subclass Composite Holiday further delegates to several other subclasses 3 CalendarDisplay Hoilday getHolidays(:Date):String[] Uses USHolidayCanadaHolidayCompostiteHoliday … 1..* Uses
Solution 4 Client ConcreteStrategy1 ConcreteStrategy2 … AbstractStrategy Operation() Uses A class in this role delegates an operation to an abstract class or interface. A class in this role provides common way to access operation encapsulated by its subclasses. Classes in this role implement alternative implementations of the operation that the client class delegate.
Consequences Client behavior dynamically determined object by object Client class simplified No need to select/implement the alternative behavior Need way to configure 5
Example Code Client 6 class CalendarDisplay {private Holiday holiday; private static final String [] noHoliday = new String[0]; … // Private class used to cache information about dates private class DateCache { private Date date; private String[] holidayStrins; DateCache (Date dt) {date = dt; … if (holiday == null) holidayStrings = noHoliday; else HolidayStrings = holiday.getHolidays(date); … } // constructor(Date) }//class DateCache … } //class CalendatDisplay
Example Code AbstractStrategy public abstract class Holiday { protected final static String [] noHoliday = new String[0]; // Return array of strings describing holidays falling on a date // If no holidays fall on the given date, returns a zero length array abstract public String[] getHolidays(Date dt); }// class Holiday 7
Example Code ConcreteStrategy public class USHoliday extends Holiday { … public String [ ] getHolidays(Date dt) { String [ ] holidays = noHoliday; … return holidays; } //getHolidays(Date) } //class USHoliday 8
Acknowledgement 9 This work was supported by a grant from Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Component Engineering (ALSACE).” This work was supported by a grant from Acxiom Corporation titled “The Acxiom Laboratory for Software Architecture and Component Engineering (ALSACE).”