Monday 15 June 2015

Strategy Design Pattern Implementation

Strategy Design Pattern

Question : - What is Strategy Design Pattern?
Answer : - This design pattern also falls under Behavioral design pattern. The Strategy design pattern deals with changing the behavior of a class by changing the internal algorithm at runtime without modifying the class itself. The Strategy Design Pattern provides the ability of selecting a specific algorithm from a family of similar algorithms at runtime in order to complete a given task.

As per GOF:- “Defines a set of encapsulated algorithms that can be swapped to carry out a specific behaviour.”

Question : - How Strategy pattern works?
Answer : -
  • defines a family of algorithms,
  • encapsulates each algorithm, and
  • makes the algorithms interchangeable within that family.
The Strategy pattern is achieved through interfaces. The business component holds a reference to an interface of an algorithm that processes a specific task. When the application is executing, the client will select a concrete algorithm implementation and pass it to the business component, which in turn will be able to process the task without knowing the details about the algorithm implementation chosen by the client.

Question : - When to use Strategy design pattern?
Answer:- If we want to select an algorithm to be used at runtime then this pattern can bes used. A nice use of the Strategy pattern would be saving files in different formats, running various sorting algorithms, or file compression.

Example of Strategy design pattern in JDK :-
a) Strategy design pattern in Java :-
  • java.util.Comparator#compare(), executed by among others Collections#sort().
  • javax.servlet.http.HttpServlet, the service() and all doXXX() methods take HttpServletRequest and HttpServletResponse and the implementor has to process them (and not to get hold of them as instance variables!).
  • javax.servlet.Filter#doFilter().
b) Real time example of Strategy design pattern:-
  • A data compression software like Winrar or WinZip which provides different algorithms to perform 7zip, jar, gip, gzip, tar formats. At runtime user selects which type of algorithm to be performed.
  • Similarly, Email client like outlook which supports various email types such as plain text, Rich Text and HTML type. It allows user to select any email format at runtime. 

Now a days, we can see the various payment methods used in shopping sites. We will try to implement the same example using this design pattern.

PaymentStrategy.java

package com.gaurav.designpattern.strategy;
/**
 * @author Gaurav
 *
 */
public interface PaymentStrategy {
public void payment(int amount);
}

CreditCardPayment.java

package com.gaurav.designpattern.strategy;

/**
 * @author Gaurav
 * 
 */
public class CreditCardPayment implements PaymentStrategy {

private CardDetails cardDetails;
public CreditCardPayment(CardDetails cardDet) {
this.cardDetails = cardDet;
}

@Override
public void payment(int amount) {
System.out.println(amount + " Rs. paid by credit card.");
}

}

WalletPayment.java

package com.gaurav.designpattern.strategy;
/**
 * @author Gaurav
 * 
 */
public class WalletPayment implements PaymentStrategy{
private String userId;
private String password;
private CardDetails cardDetails;
private String walletName;

public WalletPayment(String userName, String pwd, String walletName, CardDetails cardDet){
this.userId = userName;
this.password = pwd;
this.cardDetails = cardDet;
this.walletName = walletName;
}
@Override
public void payment(int amount) {
System.out.println(amount + " Rs. paid by "+ walletName + " wallet with credit card.");
}
}

Product.java

package com.gaurav.designpattern.strategy;

/**
 * @author Gaurav
 * 
 */
public class Product {
private String productCode;
private int price;

public Product(String code, int cost) {
this.productCode = code;
this.price = cost;
}

public String getProductCode() {
return productCode;
}

public int getPrice() {
return price;
}

}

CardDetails.java

package com.gaurav.designpattern.strategy;

/**
 * @author Gaurav
 * 
 */
public class CardDetails {

private String cardNumber;
private String cardHolderName;
private String cvv;
private String expiryDate;

public String getCardNumber() {
return cardNumber;
}

public void setCardNumber(String cardNumber) {
this.cardNumber = cardNumber;
}

public String getCardHolderName() {
return cardHolderName;
}

public void setCardHolderName(String cardHolderName) {
this.cardHolderName = cardHolderName;
}

public String getCvv() {
return cvv;
}

public void setCvv(String cvv) {
this.cvv = cvv;
}

public String getExpiryDate() {
return expiryDate;
}

public void setExpiryDate(String expiryDate) {
this.expiryDate = expiryDate;
}
}


ShoppingCart.java

package com.gaurav.designpattern.strategy;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Gaurav
 * 
 */
public class ShoppingCart {
List<Product> products = new ArrayList<Product>();;

public void addProduct(Product product) {
this.products.add(product);
}

public void removeProduct(Product product) {
this.products.remove(product);
}

public int paymentTotal() {
int sum = 0;
for (Product product : products) {
sum = sum + product.getPrice();
}
return sum;
}

public void pay(PaymentStrategy strategy) {
int amount = paymentTotal();
strategy.payment(amount);
}
}

StrategyDesignPatternDemo.java

package com.gaurav.designpattern.strategy;

/**
 * @author Gaurav
 * 
 */
public class StrategyDesignPatternDemo {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();

Product product1 = new Product("SKU208971",1499);
Product product2 = new Product("SKU098761",2099);
cart.addProduct(product1);
cart.addProduct(product2);

CardDetails cardDet = new CardDetails();
cardDet.setCardNumber("5009456700093002");
cardDet.setCardHolderName("KUMAR GAURAV");
cardDet.setCvv("804");
cardDet.setExpiryDate("09/17");
//paid the amount by credit card
cart.pay(new CreditCardPayment(cardDet));
//paid the amount by wallet
cart.pay(new WalletPayment("test_user123@jabong.com", "test123", "payTM",cardDet));
}
}

Result : - 
3598 Rs. paid by credit card.
3598 Rs. paid by payTM wallet with credit card.

No comments:

Post a Comment