24 January 2011
By: Tomas Malmsten

How to create a factory for strategies without using if’s

A recent discussion thread on the Design Patterns LinkedIn group got me thinking that a blog on how to create a factory for strategies in Java would be useful. The method below removes the need for if or switch statements.

I will start with the code and then go on to look at the details.

The Strategy interface:

The Factory class:

A strategy implementation:

Another strategy implementation:

The example code is fairly simple. The complexity lies in how to create the factory and what responsibility it should have compared to the strategies. According to the single responsibility principle a class should only have one responsibility. Therefore the strategy should not do anything else then execute. The factories responsibility is to provide strategies to the client. Therefore it's singleton instance does just that.

The client only need to know the key of the strategy it needs. This can be derived by class name, key word or something else and is stored as the key in the map that finds the correct strategy instance. To make the client logic simpler I have used Enum types to maintain keys in the past. The enum will then be able to create a valid key based on whatever is logical for the specific client.

Also note the access modifiers used for constructors. All creation logic is isolated to the package. This makes it easy to maintain since we know that nothing outside of the package can create new instances and instead has to use the factory to get an instance of the strategy.

The same recipe works well for creating other similar factories as well, for example Command factories.

Tags: Tidy Code Design Patterns