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 } }
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.