Polymorphism vs Strategy pattern

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

    I'm confused that whatever is achieved via Strategy Pattern is basically possible by polymorphism.

    You can't drive a car without a steering wheel. That does not mean that a steering wheel is a car. Similarly, the Strategy pattern relies on polymorphism but that does not mean that they are the same thing.

    The purpose of the Strategy pattern is to promote the use of composition (has-a) over inheritance (is-a). Instead of your class inheriting behavior from a super class, you define the behavior in a separate class and your class has-a reference to it.

    As far as an example goes, take a look at this answer that does a good job.

提交回复
热议问题