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.

  • generic_constructor

    Nice to find that in google, but to get rid of "ifs" is not the way to get rid of literals. Especially in my actual case I have a string, which is unique representing a special type of mail-sending process. According to that string my factory shall create a special strategy and return that. You do that hardcoded, two entries. But that is usually not the case. In real world scenarios the map gets populated during runtime. And if a string is used to differentiate among, which strategy must be created, I would prefer to see a even more generic approach. And, believe me, I am still checking out, how to map a string to a classname without any ifs. I do not believe, that this is possible at all, without introspection/reflection.