Must a class that is a "gang of four" strategy be completely stateless (ie no fields) or can it contain immutable state (ie final fields)?
One example of Strategy pattern from JDK itself is a Collections. sort() method and Comparator interface, which is a strategy interface and defines strategy for comparing objects.
A stateful object is an instance of a class that may morph itself into various states. For example an object can be created, but not initialized, later initialized and ready for being used and at the end it can be disposed (but still remain accessible in memory).
Statelessness refers to the fact that no data is preserved between runs of a strategy; i.e. if you execute the same strategy twice, nothing from the previous run of the strategy would carry over. This is beneficial in that it saves you the trouble of having to "reset" your Strategy implementations when needed.
Note that in the description of the Strategy pattern implementation they make reference to a Context (@ page 317 in my book) that contains the data the strategy needs to execute. All the 'state' required by the implementations should probably go in these context objects.
This means that the strategy implementations themselves are stateless, but the pattern as a whole has state as the required data is passed around in a context.
For example, if you had strategy implementations for mathematical operations, there are at least 2 ways to do it. The first would be to set arg1 and arg2 (and 3, and 4...) on the strategy implementations when you construct them. Then when you execute the implementation would grab its fields and do the operation. The problem is, if you run the same implementation again, you have to reset all its fields (or create a new implementation).
The second way would be to create a context that contains all the arguments. The stategy implementations would grab the values it needs off the context. Then you could reuse each instance of your strategy implementation, just passing a new context each time. No worry about recreating new instances of the implementations, or forgetting to reset the implementation instance. Of course, you still need to manage the contexts correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With