What is the difference between the Strategy
pattern and Polymorphism
in Java?
I\'m confused that whatever is achieved via Strategy Pattern is
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:
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.
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.