Behavioral Design Pattern – The Strategy Pattern

Strategy Pattern is one of the behavioral design pattern which defines a set of encapsulated algorithms that can be swapped to carry out a specific behavior at runtime without causing tight coupling. It is also known as Policy Pattern.

The Strategy pattern is to be used where you want to choose the algorithm to use at runtime.

One of the example of this pattern is Collection.sort() method that takes Comparator parameter. Based on different implementations of Comparator interfaces, the Objects are getting sorted in different ways.

On the downside, clients must be aware of different Strategies. The pattern has a potential drawback in that a client must understand how Strategies differ before it can select the appropriate one. Clients might be exposed to implementation issues. Therefore you should use the Strategy pattern only when the variation in behavior is relevant to clients.

Let’s try to illustrate the pattern with an example. Below is the class diagram for ease of reference –

classdiagram

First of all we will create the interface for our strategy:


package com.sanjit;

public interface OnlinePaymentStrategy {

public void pay(double amount);

}

Now we will have to create concrete implementations of algorithms for payment using netbanking/credit card:


package com.sanjit;

public class NetbankingPaymentStrategy implements OnlinePaymentStrategy {

/* (non-Javadoc)

* @see com.sanjit.OnlinePaymentStrategy#pay(double)

*/

@Override

public void pay(double amount) {

/*

* Logic for payment through netbanking goes here..

*/

System.out.println("Pay - " + amount + " through netbanking");

}

}

And now credit card strategy:


package com.sanjit;

public class CreditCardPaymentStrategy implements OnlinePaymentStrategy {

/* (non-Javadoc)

* @see com.sanjit.OnlinePaymentStrategy#pay(double)

*/

@Override

public void pay(double amount) {

/*

* Logic for payment through credit card goes here..

*/

System.out.println("Pay - " + amount + " through credit card");

}

}

Now our algorithms are ready and we can implement shopping item & cart. The payment method will require input as Payment strategy:


package com.sanjit;

public class ShoppingItem {

private int qty;

private double price;

public int getQty() {

return qty;

}

public void setQty(int qty) {

this.qty = qty;

}

public double getPrice() {

return price;

}

public void setPrice(double price) {

this.price = price;

}

}

The shopping cart:


package com.sanjit;

import java.util.List;

public class Cart {

private List<ShoppingItem> items;

public List<ShoppingItem> getItems() {

return items;

}

public void setItems(List<ShoppingItem> items) {

this.items = items;

}

public double calculateCartPrice() {

double cartPrice = 0;

for (ShoppingItem item : items) {

cartPrice += item.getQty() * item.getPrice();

}

return cartPrice;

}

public void pay(OnlinePaymentStrategy ops) {

ops.pay(calculateCartPrice());

}

}

Now the main class for test purpose:-


package com.sanjit;

import java.util.ArrayList;

import java.util.List;

public class Main {

/**

* @param args

*/

public static void main(String[] args) {

List<ShoppingItem> itemList = new ArrayList<ShoppingItem>();

ShoppingItem item1 = new ShoppingItem();

item1.setQty(10);

item1.setPrice(100);

itemList.add(item1);

ShoppingItem item2 = new ShoppingItem();

item2.setQty(5);

item2.setPrice(10);

itemList.add(item2);

Cart cart = new Cart();

cart.setItems(itemList);

//Pay by credit card

cart.pay(new CreditCardPaymentStrategy());

//Pay by netbanking

cart.pay(new NetbankingPaymentStrategy());

}

}

Output on running the Main class:

Pay – 1050.0 through credit card

Pay – 1050.0 through netbanking

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s