Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should the strategy pattern be stateless?

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)?

like image 944
murungu Avatar asked May 30 '11 13:05

murungu


People also ask

Which design pattern from JDK itself is the collection sort?

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.

What is stateful class in Java?

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).


1 Answers

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.

like image 88
hvgotcodes Avatar answered Oct 07 '22 19:10

hvgotcodes