Strategy Pattern

The Strategy Pattern defines family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

Suppose you are working on a payment gateway

Suppose your app requires a payment gateway like PayTm

public class PayTm{
    public void makePayment(int val){
        System.out.println("paying via paytm: " + val);
    }

}
public class PhonePay{
    public void makePayment(int val){
        System.out.println("Paying via Phonepay: " + val);
    }
}

Now in order to make code more easily updatable we can create a family of algorthims. For that we need to create an interface:

public interface PaymentMode {
    void makePayment(int val);
}

Now we have to implement this interface in the PhonePay class

public class PhonePay implements PaymentMode{
    public void makePayment(int val){
        System.out.println("Paying via Phonepay: " + val);
    }
}

Same for the PayTm class

public class PayTm implements PaymentMode{
    public void makePayment(int val){
        System.out.println("paying via paytm: " + val);
    }

}

Now in the main code what we can do is. We can create a PaymentMode variable and pass the algorithm to it so when the PaymentGateway pay is call it works according to the strategy

public class PaymentGateway {

    PaymentMode paymentMode;

    void pay(int val){
        System.out.println("payment gateway: " + val);
        paymentMode.makePayment(10);
    }

    void setPaymentStrategy(PaymentMode paymentMode){
        this.paymentMode = paymentMode;
    }

    public static void main(String[] args) {

        PaymentGateway paymentGateway = new PaymentGateway();
        paymentGateway.setPaymentStrategy(new PayTm());
        paymentGateway.pay(20);

        paymentGateway.setPaymentStrategy(new PhonePay());
        paymentGateway.pay(10);
        PayTm payTm = new PayTm();
        payTm.makePayment(10);

    }
}

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *