How to dynamically change between algorithms in runtime

My team has encountered a strange problem, we’re using a third party library to make some data available via http get request, and once a day (on average) the service become unresponsive to the requests. This forces us to restart the entire application since this data is critical for various reasons.

We’ve worked on finding the root cause and thinking abouts alternatives, but I thought that one of the suggested solutions has a wide application and that can interest others. The idea is that if there is a problem with the inner state of the objects we’re using then we would recreate them when a problem is detected.

The real difficulty is this: How do you makers everyone that got a reference to the problematic object to start using a fresh instance?

Our consideration is that we don’t want the classes using this problematic reference to be aware of this change, we didn’t want to change each and every one of them and have some method such as ReceiveGoodReference..

The change has to be transparent, and this is something that is possible to achieve via writing a decorator (don’t worry if that doesn’t say much to you, we will go over all the details).

Before I’ll show you the code and mechanics let’s talk about one application that you could use this for: Say you have two algorithms or procedures (maybe one for weekdays and another for weekends) and that you want to be changed on runtime, without the calling classes having to query the time and hold two references to both algorithms. You don’t even want the calling class to be aware that there are two algorithms! With the following method you will gain better encapsulation.

So what’s the method? As I hinted, it’s an application of a more general pattern called the Decorator design pattern.

Let’s jump to code, I’ll show the algorithms example as it is more applicable and interesting: First our two algorithms:

public class AlgorithmA
    int CalculatePriceUsingAMethod();

public class AlgorithmB
    int CalculatePriceUsingBMethod();

The first thing that we need to do is to wrap both concrete classes with an interface.

One approach is to create an interface and such as the following:

public interface IPriceCalculator
    int CalculatePrice();

and change the signatures in both concrete classes.

This is a good approach if you can change both signatures in the concrete classes without doing harm (you might have a lot of classes making calls to CalculatePriceUsingAMethod, some of which might be in different dll’s – maybe belonging to someone else!)

If you can’t take this approach then we can create another concrete class as such

public class AlgorithmAWrapper: IPriceCalculator
    public int CalculatePrice()
        //call algorithm A

Regardless of the choice, we end up with two concrete classes implementing the same interface.

Now, say we have a class that was using a specific algorithm, say algorithm A:

If this class created an instance of AlgorithmA there’s nothing we can do to change the call and route it to AlgorithmB when some conditions hold, instead we need one level of indirection — that class should not (and can’t) know which concrete class to use, only that the service is a price calculator.

What I’m getting at is passing the interface to the using class via constructor (we can do it by setting it’s property and other methods) – this is one way to do dependency injection:

public class PricePrinter
    private IPriceCalculator _calculator;
    public PricePrinter(IPriceCalculator calculator)
        _calculator = calculator;

    public void PrintPrice()
        int price = _calculator.CalculatePrice;
        //print price

Now, what about the creator of PricePrinter ? for now the call the the constructor was just

new PricePrinter(New AlgorithmA())

The PricePrinter has no clue it is using AlgorithmA  which is a good first step!

The next step is to create a class that encapsulate the logic of switching the algorithms and have it implement the same interface:

public class AlgorithmSwitcher : IPriceCalculator
    AlgorithmSwitcher(IPriceCalculator firstAlgorithm,
                        IPriceCalcualtor secondAlgorithm)
        _firstAlgorithm = firstAlgorithm;
        _secondAlgorithm = secondAlgorithm;
    public int CalculatePrice()
        //if should use algorithm A
            return _firstAlgorithm.CalculatePrice();
            return _secondAlgorithm.CalculatePrice();

We will pass a reference of our AlgorithmSwitcher to the PricePrinter:

new PricePrinter(new AlgorithmSwitcher(new AlgorithmA(),new Algorithm B()))

And this completes the changes!

Whenever PricePrinter calls calculate price it would actually call the concrete reference of AlgorithmSwitcher which in turn routes, depending on your specified condition, to one of two specific implementations.


Today we saw a specific usage of the decorator design pattern and of dependency injection (specifically – constructor injection) to achieve a very nice goal, without affecting the design and knowledge of the concrete class we already had.

I hope you’ve enjoyed this post! let me know what your’e thinking in the comments below.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at

Up ↑

%d bloggers like this: