Software Design Pattern and Strategy Design pattern

Let’s start with a quote,
If you are not prepared to be wrong, you never come up with anything original.
Sir Ken Robinson.

Software Architecture

The software design pattern is a reusable solution to the commonly occurring problem within a given context in Software Architecture. In software design, we can think about an object and organize the object in such a way that it provides a strong solution for a system. There are three categories of this design pattern.

1. Creational Design Pattern

2. Structural Design Pattern &

3. Behavioral Design Pattern.

Creational Design Pattern: It basically works for creating the object in such a manner so that the created object is flexible and reusable in the existing codes.

Structural Design Pattern: It assembles the created objects and classes into a larger structure, while it keeps the structures flexible and efficient.

Behavioral Design Pattern: It deals with the algorithms and the assignment of responsibilities between objects.

Now If we summarize the above categories, we can find that we can create objects, object structure and compose those in a way that defines a specific behavior in the software which is a better solution for a specific problem. I will discuss every pattern of software design with examples step by step with implementations.

Strategy Design Pattern:

This under the behavioral design pattern which defines the behavior of objects and algorithm to solve a certain problem in software. It can come to our mind that when we will use this design pattern. Can we think??? Ok, let’s think about you are writing code where there are several objects that are almost the same type and you have to select the object you need at your run time. You can do this with this design pattern. From the book, the main intent of this pattern is like,

“Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.”

Examples:
1. Java Collections.sort(), we can use this method for different implementations of object sorting. In the back of this method there are several algorithms are written by the JDK developers which help to sort our objects.

2. Think about we are writing code for an application where we have to write the Map API for routing, and you would need to select the path as your needs. For instance, if you look closely at the Google Map application you will see that you can select the direction as walking, bicycling, car, train, and tram as you need. In the back, you can use this pattern for selecting the path you need.

3. Suppose we are developing an e-commerce application and we need to implement the payment gateway for that, multiple payment systems can be added in the future as well but here the algorithm will not change. We will be able to add a new payment method to our design. So, we cope with anticipated and unanticipated changes to the algorithms and new algorithms or want to avoid changing code and/or breaking the existing code.

Implementation:

// Strategy interface
public interface PaymentStrategy {
public void pay(double amount);
}
// Paypal Payment Alogorithm
public class PaypalStrategy implements PaymentStrategy{

private String email;
private String password;

public PaypalStrategy(String email, String password) {
this.email = email;
this.password = password;
}

@Override
public void pay(double amount) {
System.out.println(amount + " paid by paypal");
}
}
// CreditCard Payment Algorithm
public class CreditCardStrategy implements PaymentStrategy{

private String name;
private String cardNumber;
private String cvv;
private LocalDate dateOfExpiry;

public CreditCardStrategy(String name, String cardNumber, String cvv, LocalDate dateOfExpiry) {
this.name = name;
this.cardNumber = cardNumber;
this.cvv = cvv;
this.dateOfExpiry = dateOfExpiry;
}

@Override
public void pay(double amount) {
System.out.println(amount + " Paid by credit card");
}
}

// Item
public class Item {
private String name;
private String itemCode;
private double itemPrice;

public Item(String name, String itemCode, double itemPrice) {
this.name = name;
this.itemCode = itemCode;
this.itemPrice = itemPrice;
}

public String getName() {
return name;
}

public String getItemCode() {
return itemCode;
}

public double getItemPrice() {
return itemPrice;
}
}
// Adding and calculating item price in the cartpublic class ShoppingCart {
List<Item> itemList;

public ShoppingCart() {
this.itemList = new ArrayList<>();
}

public void addItem(Item item){
itemList.add(item);
}
public void removeItem(Item item){
itemList.remove(item);
}

public double amountCalculation(){
double sum = 0.0;
for (Item item: itemList) {
sum +=item.getItemPrice();
}
return sum;
}

public void paymentStrategy(PaymentStrategy paymentStrategy){
double amount = amountCalculation();
paymentStrategy.pay(amount);
}
}
// Client Invocation for testingpublic class ShoppingCartDemo{
public static void main(String[] args) {
ShoppingCart shoppingCart = new ShoppingCart();
Item item1 = new Item("Coat","234234", 3443);
Item item2 = new Item("Shoe","543543",23423);

shoppingCart.addItem(item1);
shoppingCart.addItem(item2);

LocalDate localDate = LocalDate.now();
shoppingCart.paymentStrategy(new PaypalStrategy("abc@gmail.com","abc"));
shoppingCart.paymentStrategy(new CreditCardStrategy("Card Name",
"Card Number",
"234",localDate.plusYears(4)));

}

}

If we look at insight we will find that it supports almost all the SOLID principles in some way.

  1. The responsibility for the implementation of a concrete strategy is decoupled from the context that uses this structure.
  2. It supports OCP as we don’t need to make a change to use a new type of strategy.
  3. All the concrete strategies are using the same interface and should be substitutable without affecting the system's correctness.
  4. It supports the interface segregation principle as we don’t have any fate interface.
  5. Both the context and the concrete strategies depend on an abstract interface and are not directly coupled.

References and Books to know more:

  1. Eric Freeman, Elisabeth Robson, Kathy Sierra, and Bert Bates. Head First Design Patterns. O’ Reilly & Associates, Inc., 2014
  2. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides. Design patterns: elements of reusable object-oriented software. Addison-Wesley Professional, 1995.

Software Engineer | High Integrity System Graduate @Frankfurt University of Applied Sciences

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store