Search code examples
javasqldynamicstrategy-pattern

How to dynamically load strategies (Strategy Pattern)?


My application will have different strategies for my objects. What is the best way to implement that? Ideally, I would like to dynamically load the strategy implementations from, say, some relational database. I'm not sure how to do that, though. What's the best approach?

For instance, say that we want to apply strategy Strategy123 to object MyObj: we just load the object from a database, using its ID 123, deserialize it, get the Strategy class, and use it with MyObj.

This approach could have some issues when it comes to maintenance: while it sounds easier at a first glance, it can be a pain in the long run, for example if the strategies' interfaces change.

What other solutions do I have? I would like a solution that allows me to keep the strategy classes outside the codebase, so that I don't need to modify code and re-deploy the application if my Strategy changes, or if I add a new strategy.


Solution

  • You can implement the strategy using rules engine like Drools or some scripting language like Groovy and store these in database. Then you can load these rules from database at runtime and apply those on your object.