CS 4240: More Design Patterns Readings: Chap. 9
Let’s Recap Some Ideas and Strategies We’ll assume some design-planning is useful up-front Design with change in mind Change will happen Not sure exactly what it will be Can predict in advance where it’s likely to happen
Strategies in Response to This In anticipation of change, consider doing this: Program to an interface not an implementation Favor aggregation over inheritance Encapsulate things that will vary Even if you’re not quite sure how they may vary
Often Logic Varies Read textbook pp Example: calculating sales tax A SalesOrder object-instance must know how to calculate tax for itself Rules vary by country Rules change New countries/rules may be added
Strategy Pattern The idea: When choice of an algorithm is a dimension of variability among a family of similar things Hide this behind an interface The client codes to this interface This object is usually aggregated with another object This pairing must be established before use
Is this Common? You’ve seen the Java Comparator interface Business rules University registration system Student Bob wants to register for CS3205 Allowed or not? selectedCourse.allowReg(aStudent) Lots of logic here. Varies by course. Varies by student (on probation? too many credits?) Changes over time.
Strategy Pattern Description, part 1 Intent:Enables you to use different business rules or algorithms depending on the context in which they occur. Problem:The selection of an algorithm that needs to be applied depends on the client making the request or the data being acted on. If you just have a rule in place that does not change, you do not need a Strategy pattern. Solution:Separates the selection of algorithm from the implementation of the algorithm. Allows for the selection to be made based upon context.
Strategy Pattern Description, part 2
Strategy Pattern Description, part 3 Participants and collaborators: Strategy specifies common interface for the algorithms. ConcreteStrategies implement these different algorithms. Context linked to a specific ConcreteStrategy with a reference of type Strategy. Strategy and Context interact to implement the chosen algorithm. Context forwards requests from its client to Strategy. Sometimes Strategy must query Context.
Strategy Pattern Description, part 4 Consequences: The Strategy pattern defines a family of algorithms. Switches and/or conditionals can be eliminated. This might improve run-time efficiency! You must invoke all algorithms in the same way. (They must all have the same interface.) The interaction between the Concrete Strategies and the Context may require the addition of methods that get state to the Context.
Strategy Pattern Description, part 5 Implentation notes, etc. Client responsible for linking a Context object with a particular ConcreteStrategy This means Client must “understand” what strategies are there. So some coupling but at a higher level. Note this link is dynamic -- could change If inheritance used to define a “SubContext” class, it’s fixed Optional Strategy makes sense? Allow for Context to have null for its reference to Strategy So must check first before calling If null, Context has default behavior coded in Context
Think About and Discuss Are State and Strategy DPs similar? The same? How different? Suggestion: look up Web resources to learn more.
Strategy Examples Java comparator objects? Collections.sort(theList, new MyComparator()); How does this match the pattern? How not?
java.util.zip Two classes need an algorithm for calculating check-sums CheckedInputStream, CheckedOutputStream Two algorithms defined that meet CheckSum interface Adler32 and CRC32 Constructors for first two classes get an instance of Checksum
java.util.zip and Checksum interface Interface Checksum: long getValue() : Returns the current checksum value.getValue void reset() : Resets the checksum to its initial value.reset void update(byte[] b, int off, int len) : Updates the current checksum with the specified array of bytes.update void update(int b) : Updates the current checksum with the specified byte.update
Other Examples Input field validation in GUIs Valid type, range, values, etc. A Validate interface hides algorithm/logic used Each input-field linked to a Validate instance All fields told to validate() their contents Memory allocation (a la C/C++) Get memory chunks, return chunks But could involve memory-pools, caches, locks, other management
Note: Again, here’s class that more like an operation than a “thing” or entity
END