Java implementation of Strategy Pattern

     This design pattern deals with Dynamic Behavior Selection. Without modifying the code, the pattern swaps the behavior at run time.

Technical implementation:

This implementation starts with creating interface.

  • ‘interface’ PaymentMethod is developed with a member function payIt().payIt() has a member variable ‘amount’.
  • Two classes “CCPayment” and “BankPayment” are derived from interface PaymentMethod.
  • “payIt() method displays the amount paid message to the user.
  • PaymentContext is a class for developing this design pattern.
  • A private member variable’ meth’ is created for PaymentMethod interface.
  • ‘setMethod()’ initialises the variable ‘meth’.
  • ‘processIt()’ calls the function ‘payIt()’ with ‘amount’ value.
  • Finally, a sample class with main () function is written.
  • An object is created for PaymentContext.
  • First,setMethod is initialised with CCPayment object.
  • It calls the payIt() functions with amount value.
  • Again,the setMethod is initialised with BankPayment object.
  • It calls the payIt() function with amount value.

Program:

interface PaymentMethod {

    void payIt(int amount);

}

class CCPayment implements PaymentMethod {

    public void payIt(int amount) {

        System.out.println("The amount: "+amount + "is paid via Credit Card.");

    }

}

class BankPayment implements PaymentMethod {

    public void payIt(int amount) {

        System.out.println("The amount: " + amount + " is paid via Bank account.");

    }

}

class PaymentContext {

    private PaymentMethod meth;

    public void setMethod(PaymentMethod meth) {

        this.meth = meth;

    }

    public void processIt(int amount) {

        meth.payIt(amount);

    }

}

public class sample {

    public static void main(String[] args) {

        PaymentContext pm = new PaymentContext();

        pm.setMethod(new CCPayment());

        pm.processIt(5000);

        pm.setMethod(new BankPayment());

        pm.processIt(1500);

    }

}

Output:

Compile and run the program to get the output.

C:\raji\blog>javac sample.java

C:\raji\blog>java sample

The amount: 5000 is paid via Credit Card.

The amount: 1500 is paid via Bank account.

This design pattern is useful in payment gateways. It also useful in developing AI algorithms.

That’s all. The java program to implement the Strategy Design Pattern is done. Hope, this code sample is useful to you. Keep Coding!!!

No comments:

Post a Comment