strategy

Implement a shopping cart using the Strategy Pattern

First a definition: in the simplest terms, you can define the Strategy Pattern as telling an object to do a job and to do it using ANOTHER object.

To clarify this further I’m going to redesign the ShoppingCart slightly, by giving it a pay()* method:

public class ShoppingCart {

  private final List<Item> items;

  public ShoppingCart() {
    items = new ArrayList<Item>();
  }

  public void addItem(Item item) {

    items.add(item);
  }

  public double calcTotalCost() {

    double total = 0.0;
    for (Item item : items) {

total += item.getPrice();
    }

    return total;
  }

  public boolean pay(PaymentMethod method) {

    double totalCost = calcTotalCost();
    return method.pay(totalCost);
  }
}

The thing to notice about the pay() method is that it takes one parameter of type PaymentMethod – it’s the PaymentMethod that’s the “ANOTHERâ€� object in my definition above.

The next thing to do is define the PaymentMethod as an interface. Why an interface? It’s because the power of this technique is that you can decide at run-time which concrete type you’ll pass into the ShoppingCart to make the payment. For example, given the Payment interface:

public interface PaymentMethod {

  public boolean pay(double amount);

}

you can then define any concrete payment object such as a Visa or a MasterCard for example:

public class Visa implements PaymentMethod {

  private final String name;
  private final String cardNumber;
  private final Date expires;

  public Visa(String name, String cardNumber, Date expires) {
    super();
    this.name = name;
    this.cardNumber = cardNumber;
    this.expires = expires;
  }

  @Override
  public boolean pay(double amount) {

    // Open Comms to Visa
    // Verify connection
    // Paybill using these details
    return true; // if payment goes through
  }

}

…and

public class MasterCard implements PaymentMethod {

  private final String name;
  private final String cardNumber;
  private final Date expires;

  public MasterCard(String name, String cardNumber, Date expires) {
    super();
    this.name = name;
    this.cardNumber = cardNumber;
    this.expires = expires;
  }

  @Override
  public boolean pay(double amount) {

    // Open Comms to Mastercard
    // Verify connection
    // Paybill using these details
    return true; // if payment goes through
  }

}


Related Article:

Reference: The Strategy Pattern from our JCG partner Roger Hughes at the Captain Debug’s Blog blog.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button