The Strategy Pattern

In a recent blog on I received a comment from Wojciech Soczy?ski about how the “strategy” pattern can be used to enforce the Single Responsibility Principle (SRP) when using Tell Don’t Ask (TDA). At some point I plan to discuss this further, but first thought that it would be a good idea to define the Strategy Pattern using the ShoppingCart example that I used a couple of weeks ago in my Tell Don’t Ask and its follow up Disassembling Tell Don’t Ask blogs:

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
  }

}


The final thing to do is to demonstrate this with the unit test: payBillUsingVisa

@Test
  public void payBillUsingVisa() {

    ShoppingCart instance = new ShoppingCart();

    Item a = new Item("gloves", 23.43);
    instance.addItem(a);

    Item b = new Item("hat", 10.99);
    instance.addItem(b);

    Date expiryDate = getCardExpireyDate();
    PaymentMethod visa = new Visa("CaptainDebug", "1234234534564567", expiryDate);

    boolean result = instance.pay(visa);
    assertTrue(result);

  }

  private Date getCardExpireyDate() {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    cal.set(2015, Calendar.JANUARY, 21);
    return cal.getTime();
  }

In the code above, you can see that I’m creating a ShoppingCart and then I add a few items. Finally, I create a new PaymentMethod in the form of a Visa object and inject it into the pay(PaymentMethod method) function, which is the crux of the matter. In a different situation I could have easily created a MasterCard object and used that as a direct replacement for Visa – i.e. the object that which is passed in as an argument is determined at runtime.

And that defines the Strategy pattern, but that’s not the end of the blog. If you’ve ever used Spring, but never heard of the Strategy pattern, all this should feel a little familiar. This is because it turns out that the Guys at Spring use the Strategy Pattern to underpin their whole technology. If I take my example above and make a few slight changes I can come up with:

@Component
public class SpringShoppingCart {

  private final List<Item> items;

  @Autowired
  @Qualifier("Visa")
  private PaymentMethod method;

  public SpringShoppingCart() {
    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() {

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

The only difference between this incarnation and the first one is that the strategy class Visa is injected by Spring when the class is loaded using the @Autowired annotation. To sum this up, I guess guess that this means that the Strategy Pattern is the most popular pattern in the world.

*For the purposes of this discussion I’m assuming that it’s okay for a ShoppingCart to pay for itself, but whether this is correct or not is a whole new blog…

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

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


× 1 = three



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close