c# - How does the strategy pattern differ from polymorphism? -


in computer programming, strategy pattern (also known policy pattern) behavioural software design pattern enables algorithm's behavior selected @ runtime.

the strategy pattern...

  • defines family of algorithms.
  • encapsulates each algorithm.
  • makes algorithms interchangeable within family.

(source: wikipedia)

in case, want able inject different hashing algorithms service. c# has several hashing algorithms derive hashalgorithm, such as:

  • md5
  • sha256managed
  • ripemd160managed

given hierarchy, looks strategy pattern, had never heard of strategy pattern, might classic example of polymorphism.

whilst designing code solve particular problem, designed interface based on strategy pattern 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 previous example, equally rid of interface altogether , use hashalgorithm:

public sealed class hashcreator {     public hash gethash(hashalgorithm algorithm, byte[] data)     {         return new hash(algorithm.computehash(data));     } } 

question 1: strategy pattern different in way polymorphism, or because of polymorphism strategy pattern exists?

question 2: considered better practice here; abstract out functionality require interface (ihashstrategy) or use base type (hashalgorithm)?

polymorphism feature of oo-languages, allows have 1 interface different types. strategy conceptual pattern, uses polymorphism in oo language, can done functions in functional programming example.

as mentioned,

the strategy pattern (also known policy pattern) behavioural software design pattern enables algorithm's behavior selected @ runtime

so, not polymorphism, can set different strategies object behavior, can change strategy example, object can have few strategies, different objects can have same strategy, objects of 1 type can have different strategies, there point. polymorphism 1 way(the best 1 oo languages imho), how implement it.


Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -