Patterns 101: The Strategy Pattern

By Joe Hubert
Page 4 of 4

Summary

In this example, I show how the Strategy pattern can be used to encapsulate an important aspect of application requirements. By using a Factory Method to return the appropriate Strategy, I demonstrate a typical design pattern interaction. Maybe you can try this approach on an existing application. Look for a case where the business rules or algorithms vary based on the changing values of some application or environment parameters (customer type, day of week, monetary threshold, and so forth).

Finally, there are some buzzwords in the pattern realm that you should understand in your further reading about patterns. We have either mentioned these terms directly or exercised their intent. Let's review these terms as they were demonstrated in the context of this article:

Decoupling

Allowing independent (not necessarily 'unrelated') elements within a system to vary independently. By keeping my base applicant code in one class and my validation code in another class, I have decoupled the elements in my design. Again, this proper organization of code shouldn't be undervalued. Code should be organized in proper classes for the same reason that documents for separate projects are often stored in separate manila folders. The code in each of these classes can vary independently (to some reasonable extent).

Delegation

The 'outsourcing' of algorithmic responsibilities from one object (the delegator) to another (the implementer). The form objects in our example didn't deal with the specifics of validation. The form must support a validate() method, but it relies on an independent class hierarchy to implement the details of validation. The form delegates its validation to the FormValidation classes.

Cohesion

Commitment to a single or limited functional purpose within the scope of a system. By limiting my validation and applicant classes to their particular business concerns, I have given them strong focus and have created a cohesive design.

So that's it. The understanding of these concepts is very achievable and the consequences of good software design should be more apparent. Any light bulbs? Let me know.

-Joe

Feedback

Articles
Factory 101

Strategy 101