Java Strategy Pattern – Implementing Strategy Pattern via Configuration

design-patternsjavastrategy-pattern

In my current problem domain, a number of problems seem to lend themselves quite well to the strategy pattern. I have a common, high-level process – let's say it's a sales process – and regardless of the sales channel I use, sellProduct needs to happen… It's just a bit different from channel to channel.

So let's say I want to implement a strategy pattern per-channel.

What I'd really like to know, is whether there's a robust, common way that people have seen this implemented. Typically what I've seen in the past is some kind of lookup, perhaps from a DB or config file, based on the channel type, that instantiates a particular class and then executes SalesStrategy.execute() on that implementation. That said, I'm not sure if storing fully-qualified class names in a DB or config file is really the best we can do here.

Does anyone else have other thoughts? I'm using Java, so interested in what sort of common configuration-based solutions people have used through something like Guice or Spring.

Best Answer

No, your database/config files should not mention class names.

Instead, you should include the channel in your model, as it is a relevant part of your domain. This doesn't have to be fancy - a simply enum may be sufficient. If your strategy depends on many parameters, you can group them into a SalesStrategyConfiguration.

The actual strategy is then instantiated by a factory, which evaluates the provided parameters and instantiates the correct strategy. This decision is based purely on domain-relevant concepts, so there is no need for any specific framework.

Where a framework may well come in handy is the translation of the config data to the model (i.e. creating the SalesStrategyConfiguration). But this is a very general task, in no way related to strategy instantiation.

Related Topic