Polymorphism vs Strategy pattern

后端 未结 10 939
陌清茗
陌清茗 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:05

    Polymorphism vs Strategy pattern with core java examples

    • Basic difference : Polymorphism is programming language concept, and Strategy pattern is one of behavioral design pattern of GoF.

    • Polymorphism is the provision of a single interface to entities of different types.
      Example: The steering wheel(i.e., the interface) is same no matter what type of actual steering mechanism is used. That is, the steering wheel works the same whether your car has manual steering, power steering, or rack-and-pinion steering. Therefore once you know how to operate the steering wheel, you can drive any type of car.

    • In programming, Polymorphism implemented in two ways:

      • Early-Binding/Static/Compile-Time Polymorphism (ex: function overloading)
      • Late-Binding/Dynamic/Run-Time Polymorphism (ex: function overriding)

    Compile-time: the time period in which you, the developer, are compiling your code.
    Run-time: the time period which a user is running your piece of software.
    Source

    • A Strategy pattern defines a set of algorithms that can be used interchangeably.

      • The Strategy pattern is a dynamic pattern (How do you want run a behavior in software?).
      • Example of core java: java.util.Comparator#compare(), executed by among others Collections#sort().

      • Modes of transportation is analogous to strategy design pattern. We use car, bike, bus, local train and so on.. different strategies to go office day by day.

提交回复
热议问题