personal-page/_master_wiki/Readwise/02. Strategy Pattern.md

2.3 KiB

02. Strategy Pattern

rw-book-cover

Metadata

[!tldr] #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 a...

Highlights

The second pattern we're going to  look into is the Strategy Pattern.  This pattern sets up several methods, or  'strategies', for performing a particular task,  and allows them to be 'interchanged' as needed View Highlight)

This pattern separates several algorithms that   perform specific functions  into individual capsules,  thus allowing them to be switched out  at any point during code execution.  If a new method needs to be added, you can  easily extend by creating another strategy class,  and it also becomes possible  to reuse them in other places. View Highlight)

This would be code that adheres to the  'Open/Closed Principle' we learned from SOLID. View Highlight)