Where is the benefit in using the Strategy Pattern?

前端 未结 8 1082
太阳男子
太阳男子 2020-12-28 10:22

I\'ve looked at this explanation on Wikipedia, specifically the C++ sample, and fail to recognize the difference between just defining 3 classes, creating instances and call

8条回答
  •  伪装坚强ぢ
    2020-12-28 10:57

    This design pattern allows to encapsulate algorithms in classes.

    The class that uses the strategy, the client class, is decoupled from the algorithm implementation. You can change the algorithms implementation, or add new algorithm without having to modify the client. This can also be done dynamically: the client can choose the algorithm he will use.

    For an example, imagine an application that needs to save an image to a file ; the image can be saved in different formats (PNG, JPG ...). The encoding algorithms will all be implemented in different classes sharing the same interface. The client class will choose one depending on the user preference.

提交回复
热议问题