Strategy Design Pattern in Java tutorial

The strategy design pattern falls under the category of behavioral design patterns. It is employed when there are various algorithms available for a particular task, and the client determines the particular implementation to be used at runtime.

One possible native paraphrase for “Strategy Pattern” could be “Approach Methodology”.

The Strategy pattern, also referred to as the Policy Pattern, involves defining numerous algorithms and allowing the client application to pass the desired algorithm as a parameter. An exemplary instance of the strategy pattern is the Collections.sort() method, which takes a Comparator parameter. Depending on the various implementations of the Comparator interface, the objects are sorted in different manners. To illustrate, let’s create a simple Shopping Cart that encompasses two payment strategies: using a Credit Card or using PayPal. Initially, we will establish the interface for our strategy pattern example, which entails paying the specified amount. This interface will be named PaymentStrategy.java.

package com.scdev.design.strategy;

public interface PaymentStrategy {

	public void pay(int amount);
}

We are now required to develop practical implementations of algorithms for processing payments via credit/debit cards or PayPal. This will be done through the utilization of the CreditCardStrategy.java file.

package com.scdev.design.strategy;

public class CreditCardStrategy implements PaymentStrategy {

	private String name;
	private String cardNumber;
	private String cvv;
	private String dateOfExpiry;
	
	public CreditCardStrategy(String nm, String ccNum, String cvv, String expiryDate){
		this.name=nm;
		this.cardNumber=ccNum;
		this.cvv=cvv;
		this.dateOfExpiry=expiryDate;
	}
	@Override
	public void pay(int amount) {
		System.out.println(amount +" paid with credit/debit card");
	}

}

One possible paraphrase could be:

“Java code file for the PayPal payment strategy.”

package com.scdev.design.strategy;

public class PaypalStrategy implements PaymentStrategy {

	private String emailId;
	private String password;
	
	public PaypalStrategy(String email, String pwd){
		this.emailId=email;
		this.password=pwd;
	}
	
	@Override
	public void pay(int amount) {
		System.out.println(amount + " paid using Paypal.");
	}

}

Our algorithms for the strategy pattern example are now prepared. The implementation of the Shopping Cart and payment method will necessitate the input of a Payment strategy in Item.java.

package com.scdev.design.strategy;

public class Item {

	private String upcCode;
	private int price;
	
	public Item(String upc, int cost){
		this.upcCode=upc;
		this.price=cost;
	}

	public String getUpcCode() {
		return upcCode;
	}

	public int getPrice() {
		return price;
	}
	
}

One possible paraphrase for “ShoppingCart.java” could be “Java code for a shopping cart.”

package com.scdev.design.strategy;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class ShoppingCart {

	//List of items
	List<Item> items;
	
	public ShoppingCart(){
		this.items=new ArrayList<Item>();
	}
	
	public void addItem(Item item){
		this.items.add(item);
	}
	
	public void removeItem(Item item){
		this.items.remove(item);
	}
	
	public int calculateTotal(){
		int sum = 0;
		for(Item item : items){
			sum += item.getPrice();
		}
		return sum;
	}
	
	public void pay(PaymentStrategy paymentMethod){
		int amount = calculateTotal();
		paymentMethod.pay(amount);
	}
}

Please take note that the payment method of the shopping cart necessitates the payment algorithm as an argument and does not retain it as a variable. Let’s evaluate our strategy pattern example setup using a basic program named ShoppingCartTest.java.

package com.scdev.design.strategy;

public class ShoppingCartTest {

	public static void main(String[] args) {
		ShoppingCart cart = new ShoppingCart();
		
		Item item1 = new Item("1234",10);
		Item item2 = new Item("5678",40);
		
		cart.addItem(item1);
		cart.addItem(item2);
		
		//pay by paypal
		cart.pay(new PaypalStrategy("myemail@example.com", "mypwd"));
		
		//pay by credit card
		cart.pay(new CreditCardStrategy("Pankaj Kumar", "1234567890123456", "786", "12/15"));
	}

}

The program above produces the following result:

50 paid using Paypal.
50 paid with credit/debit card

One possible paraphrase could be: “Class Diagram for the Strategy Design Pattern”

Important considerations for the Strategy design pattern.

  • We could have used composition to create instance variable for strategies but we should avoid that as we want the specific strategy to be applied for a particular task. Same is followed in Collections.sort() and Arrays.sort() method that take comparator as argument.
  • Strategy Pattern is very similar to State Pattern. One of the difference is that Context contains state as instance variable and there can be multiple tasks whose implementation can be dependent on the state whereas in strategy pattern strategy is passed as argument to the method and context object doesn’t have any variable to store it.
  • Strategy pattern is useful when we have multiple algorithms for specific task and we want our application to be flexible to chose any of the algorithm at runtime for specific task.

I hope you enjoyed my explanation of the Strategy Pattern in Java, and that concludes our discussion on this topic.

 

more  tutorials

Java thread ensuring Java code is thread-safe(Opens in a new browser tab)

convert string to character array in Java.(Opens in a new browser tab)

Addition Assignment Operator mean in Java(Opens in a new browser tab)

Leave a Reply 0

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