June 7, 2020
Hot Topics:

Working with Design Patterns: Strategy

  • By Jeff Langr
  • Send Email »
  • More Articles »

I need to ensure that the OracleDateFormatter is usable. I could write an additional test in DateColumn. Or, I could take a shortcut and alter the test:

public void initialize() {
   formatter = new OracleDateFormatter();
   column = new DateColumn(NAME, formatter);

That change forces OracleDateFormatter to implement the interface:

public class OracleDateFormatter implements DateFormatter {

The unit tests verify everything that I've implemented to this point. Missing, someplace, is the client code that uses DateColumn. This client code is responsible for passing the correct type of formatter into each DateColumn instance. Perhaps this logic is part of a factory, for which I can easily write a unit test.

For purposes of the strategy pattern, my work is done. When a client asks the DateColumn class to provide a value string, it delegates its work to an appropriate DateFormatter instance. The code in DateColumn is oblivious of the DBMS type for which it's doing the work. There's no need for an "if" statement in DateColumn. The DateColumn class is "closed" for modification, at least with respect to changes in date formatting logic.

In Conclusion

I was able to arrive at a cool pattern implementation by virtue of very small, incremental steps. It's "cool" to me because each of the classes that comprise the pattern are small and easy to understand. Better, everything flowed naturally as a result of my interest in driving the implementation through tests, and everything ended up very easy to test. Once again, unit testing via test-driven development (TDD) has helped me produce a solution that is in alignment with notions of good design.


[Gamma] Gamma, E., et. al. Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley Professional, 1995, p315.

About the Author

Jeff Langr is a veteran software developer celebrating his 25th year of professional software development. He's authored two books and dozens of published articles on software development, including Agile Java: Crafting Code With Test-Driven Development (Prentice Hall) in 2005. You can find out more about Jeff at his site, http://langrsoft.com, or you can contact him via email at jeff at langrsoft.com.

Page 3 of 3

This article was originally published on June 13, 2007

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date