Behavioural - Strategy Pattern
It helps to define multiple Strategies for the same task and user can select any strategy

Low Level Design

Client chooses which algorithm (strategy) to use.
Object chooses its next state based on internal rules.
Focus: interchangeable algorithms.
Focus: behavior changes over time based on state transitions.
The object’s behavior doesn’t change by itself; caller sets the strategy.
The object’s behavior changes automatically when its internal state changes.
Client controls switching.
Context controls switching.
Implementation
Interface
public interface PaymentStrategy {
void pay();
}Different Payment Strategies
public class UPIStrategy implements PaymentStrategy {
@Override
public void pay() {
System.out.println("UPI payment");
}
}public class NetBankingStrategy implements PaymentStrategy {
@Override
public void pay() {
System.out.println("Paying via internet banking");
}
}public class CreditCardStrategy implements PaymentStrategy {
@Override
public void pay() {
System.out.println("Paying via credit card);
}
}Context Class
public class ShoppingCart { // Can be Abstract class in case of various shoping cart (mobile/web)
PaymentStrategy paymentStrategy;
ShoppingCart(PaymentStrategy paymentStrategy) {
this.paymentStrategy = paymentStrategy;
}
void makePayment() {
paymentStrategy.pay();
}
}
Customer
public class Customer {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart(new CreditCardStrategy());
cart.makePayment();
//Another order
ShoppingCart cart = new ShoppingCart(new NetBankingStrategy());
cart.makePayment();
}
}Some other examples
sorting strategies like Insertion Sort, Merge Sort etc.
Allocation Strategies like Round-Robin Algorithm, Hashing Strategye etc.
Comparator Example = Strategy
Collections.sort(list, Comparator.reverseOrder()); // Client decides strategyIf the client switches strategy:
Collections.sort(list, Comparator.naturalOrder()); // Client changes behaviorBehavior changes because the client selected a different strategy.
Last updated
Was this helpful?