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.

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

Leave a Reply


one + 1 =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books