02. Strategy pattern

preview_player
Показать описание
#OODP #ObjectOrientedDesignPattern #ObjectOriented

The Strategy pattern is a pattern that allows you to switch between several specific operation methods as needed. It creates several 'modes', each performing a given function, and allows you to choose which one to use. For example, shopping carts at a large supermarket's checkout counter perform the 'payment' function in various ways.

This is illustrated in an example of implementing the Strategy pattern, creating an interface called 'PaymentStrategy', and creating two classes that implement it, 'CreditCardPayment' and 'PayPalPayment'. These two classes fall into the 'PaymentStrategy' category, each implementing a 'pay' method. The important point here is that objects of the two classes can take the place of the 'PaymentStrategy' and execute the 'pay' method.

Also, the 'ShoppingCart' class has a 'PaymentStrategy' field, and the 'pay' method of the selected strategy is executed when calculating. In this way, the strategy pattern allows not only to change the algorithm as much as possible during code execution, but also to create a new strategy class if needed, and reuse it elsewhere.

As a result, the strategy pattern helps to create code that complies with the SOLID 'Open/Closed Principle'.
Рекомендации по теме
Комментарии
Автор

Great explanation as always! Keep it up!

tomaszbrewka