mercredi 28 décembre 2016

How does the strategy pattern differ from polymorphism?

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 class HashCreator : IHashCreator
{
    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 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)?

Aucun commentaire:

Enregistrer un commentaire