Let's look at two ways of implementing a basic strategy pattern for a Calculator class that performs a calculation implemented as a strategy. I'll attempt to make the surface areas of each class the same so we can look at the different requirements needed to implement the pattern through traditional OOP and then by using delegates.
To start, we will be using a common enumerator to define the different methods our Calculator class can perform:
When we implement, we want to code that looks like the following where we set the calculation strategy using the previously CaluclationType enum:
Part I. OOP Implementation
To get started with the OOP implementation of our solution we'll need an interface that defines the strategy we are implementing:
And then use this interface in all the different calculations we'll be needing:
Next, we'll define our OopCalculator class that executes the strategy. The constructor is going to be passed the CaluclationType enum. We need to keep member variables for the strategy and the enumerator and we'll have a helper method to instantiate the correct class implementing our ICalculate strategy.
Ok, so in the end we are left with one main class, one interface (which could have been an abstract base class as well), four strategy classes and our main class all in approximately 100 lines of code.
Part II. Delegate implementation
In our delegate implementation, we'll be using a delegate in place of the strategy interface so let's first define a really generic delegates as follows:
And the only other thing we'll be needing is the implementing class. It will have the same constructor as our OopCalculator and be implemented exactly the same. We'll have a switch statement just like in the OOPCalculator to get the correct strategy. The main difference is that all the methods containing the calculations will be internal to the class which we'll be wiring up with delegates:
So in the end using the delegate approach we are left with one main class, one delegate (which can be reused because it's so generic) and around 60 lines of code. That's significantly less code, classes and resulting complexity to keep track of because we no longer have to have an individual object representing each strategy.
Hopefully this gives you some insight as to the power and usefulness of delegates.
Until next time,
Happy coding