Strategy Pattern Demo

PaymentStategy Interface

package StrategyPatternDemoOne; // Strategy interface interface PaymentStrategy { void pay(double amount); }
package StrategyPatternDemoOne; class PayPalStrategy implements PaymentStrategy { private String email; private String password; public PayPalStrategy(String email, String password) { this.email = email; this.password = password; } public void pay(double amount) { System.out.println("Paying " + amount + " with PayPal."); // Perform the payment logic using PayPal credentials } }
package StrategyPatternDemoOne; // Concrete strategies class CreditCardStrategy implements PaymentStrategy { private String cardNumber; private String expiryDate; private String cvv; public CreditCardStrategy(String cardNumber, String expiryDate, String cvv) { this.cardNumber = cardNumber; this.expiryDate = expiryDate; this.cvv = cvv; } public void pay(double amount) { System.out.println("Paying " + amount + " with credit card."); // Perform the payment logic using credit card details } }

Driver:

In the example above, the PaymentStrategy interface defines a contract for payment strategies, and CreditCardStrategy and PayPalStrategy are concrete implementations of the payment algorithm. The ShoppingCart class contains a reference to a PaymentStrategy object, which can be set dynamically. The client code can change the payment strategy by calling the setPaymentStrategy() method.

By applying the Strategy pattern, the client code can switch between different payment strategies without modifying the core logic of the ShoppingCart class. This flexibility is especially useful when you have multiple algorithms or behaviors that need to be dynamically selected or replaced based on varying requirements.