Strategy Design Pattern
TheĀ Ā is aĀ Ā that allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern enables a client (like a class or object) to select an algorithm's behavior at runtime, without modifying the code. It's useful when you have multiple variations of a common task and want to avoid conditional statements or repetitive code.
Problem:
When subclasses (children) inherit from a parent but do not utilize the parent's common functionality, they end up overriding the functionality, which can lead to code duplication across child classes(as same code is implemented by multiple child classes).
Solution:
To avoid code duplication among subclasses, the Strategy Pattern suggests creatingĀ Ā for the different algorithms (behaviors). Each subclass can then use a strategy instead of implementing its own version of the behavior. This avoids code duplication, adheres to theĀ , and allows the behavior to be selected dynamically.
Ā

Ā
Code:
package com.design.strategy; public interface PaymentStrategy { public void pay(int amount); }
Ā
package com.design.strategy; public class CreditCardStrategy implements PaymentStrategy { private String name; private String cardNumber; private String cvv; private String dateOfExpiry; public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){ this.name=nm; this.cardNumber=ccNum; this.cvv=cvv; this.dateOfExpiry=expiryDate; } @Override public void pay(int amount) { System.out.println(amount +" paid with credit/debit card"); } }
Ā
package com.design.strategy; public class PaypalStrategy implements PaymentStrategy { private String emailId; private String password; public PaypalStrategy(String email, String pwd){ this.emailId=email; this.password=pwd; } @Override public void pay(int amount) { System.out.println(amount + " paid using Paypal."); } }
Ā
package com.design.strategy; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class ShoppingCart { //List of items List<Item> items; public ShoppingCart(){ this.items=new ArrayList<Item>(); } public void addItem(Item item){ this.items.add(item); } public void removeItem(Item item){ this.items.remove(item); } public int calculateTotal(){ int sum = 0; for(Item item : items){ sum += item.getPrice(); } return sum; } public void pay(PaymentStrategy paymentMethod){ int amount = calculateTotal(); paymentMethod.pay(amount); } }
Ā
Ā
public class ShoppingCartTest { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); Item item1 = new Item("1234",10); Item item2 = new Item("5678",40); cart.addItem(item1); cart.addItem(item2); //pay by paypal cart.pay(new PaypalStrategy("myemail@example.com", "mypwd")); //pay by credit card cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15")); } }