Strategy Pattern in TypeScript
Introduction to the Strategy Pattern
Welcome back! We are continuing our journey through Behavioral Patterns in software design. In previous lessons, we explored the Command and Observer patterns, focusing on object communication and state changes. Now, we will learn how to implement the Strategy Pattern in TypeScript. We will break down the pattern into manageable parts and illustrate its practical application through a clear example.
Consider a scenario in which you have a ShoppingCart class that can handle payments through different methods, such as credit cards or PayPal. Using the Strategy Pattern, we can encapsulate these payment methods into separate classes and have the ShoppingCart class use any of these strategies interchangeably.
Strategy Interface
First, we define an interface that all payment strategies will follow. In TypeScript, interfaces provide a clear contract for classes to implement, ensuring type safety and consistency.
Here, the PaymentStrategy interface declares a pay method that accepts an amount of type number and returns nothing (void). Any payment strategy must implement this method.
Concrete Strategies
Next, we implement concrete strategies that encapsulate different payment methods. Here, we define two strategies: CreditCardStrategy and PayPalStrategy. Each class implements the PaymentStrategy interface and provides its own logic for the pay method.
In the CreditCardStrategy class, we implement the pay method to handle credit card transactions. This class requires a card number upon initialization, which is stored as a private property.
Similarly, the PayPalStrategy class implements the pay method for PayPal transactions. It requires an email address to initialize, which is stored as a private property.
