Polymorphism vs Strategy pattern

后端 未结 10 940
陌清茗
陌清茗 2021-01-30 10:12

What is the difference between the Strategy pattern and Polymorphism in Java?

I\'m confused that whatever is achieved via Strategy Pattern is

10条回答
  •  一个人的身影
    2021-01-30 11:13

    First of all. Polymorphism can mean two different things. Most commonly polymorphism refers to a polymorphic type. However, you are asking for the pattern.

    Polymorphic code can change itself each time it runs while the function of the code stays the same. An easy example is to do 1+3=4 instead of 5-1=4. Both achieves the same result using different code. This is useful for code that does not want to be recognized i.e computer viruses or cryptographic code.

    Strategy pattern on the other hand uses a family of algorithms that can be interchanged. This might be used when translating text. First some code determines the language. if the language is swedish or spanish the text will be processed by, different functions of the same family, translateSwedish() or translateSpanish().

    To round things up. Polymorphic code uses different code that achieves the same result. While Strategy uses different code to achieve better results.

提交回复
热议问题