In computer programming, the strategy pattern (also known as the policy pattern) is a behavioural software design pattern that enables an algorithm's behavior to be selected at runtime.
The strategy pattern...
- Defines a family of algorithms.
- Encapsulates each algorithm.
- Makes the algorithms interchangeable within that family.
(source: Wikipedia)
In my case, I want to be able to inject different hashing algorithms into a service. C# has several hashing algorithms that derive from HashAlgorithm, such as:
- MD5
- SHA256Managed
- RIPEMD160Managed
Given this hierarchy, this looks like the strategy pattern, but had I never heard of the strategy pattern, I might just say this was a classic example of polymorphism.
Whilst designing the code to solve my particular problem, I designed an interface based on the strategy pattern to inject different hashing algorithms:
public interface IHashStrategy
{
Hash ComputeHash(byte[] data);
}
Usage
public sealed class HashCreator
{
public Hash GetHash(IHashStrategy strategy, byte[] data)
{
return strategy.ComputeHash(data);
}
}
Going back to my previous example, I could equally get rid of the interface altogether and just use HashAlgorithm
:
public sealed class HashCreator
{
public Hash GetHash(HashAlgorithm algorithm, byte[] data)
{
return new Hash(algorithm.ComputeHash(data));
}
}
Question 1: Is the strategy pattern different in any way from polymorphism, or is it because of polymorphism that the strategy pattern exists?
Question 2: Which is considered better practice here; abstract out the functionality I require into an interface (IHashStrategy
) or use the base type (HashAlgorithm
)?
Polymorphism is just a feature of OO-languages, that allows you to have one interface for different types. Strategy is conceptual pattern, that uses polymorphism in OO language, as it can be done with functions in functional programming for example.
As you mentioned,
so, it is not only the polymorphism, you can set different strategies for object behavior, you can change the strategy for example, your object can have few strategies, different objects can have the same strategy, objects of one type can have different strategies, there is a point. Polymorphism is just the one way(the best one for OO languages imho), how you could implement it.