Field Notes: Using the Strategy Pattern

I had been using the e-tail example in my pattern classes when someone asked, “Are you aware that in the UK people over a certain age don't get taxed on food?” I wasn't aware of this and the interface for the CalcTax object did not handle this case. I could handle this in at least one of three ways:

  1. Pass the age of the Customer into the CalcTax object and use it if needed.

  2. Be more general by passing in the Customer object itself and querying it if needed.

  3. Be more general still by passing a reference to the SalesOrder object (that is, this) and letting the CalcTax object query it.

While it is true I have to modify the SalesOrder and CalcTax classes to handle this case, it is clear how to do this. I am not likely to introduce a problem because of this.

Technically, the Strategy pattern is about encapsulating algorithms. However, in practice, I have found that it can be used for encapsulating virtually any kind of rule. In general, when I am doing analysis and I hear about applying different business rules at different times, I consider the possibility of a Strategy pattern handling this variation for me.

The Strategy pattern requires that the algorithms (business rules) being encapsulated now lie outside of the class that is using them (the Context). This means that the information needed by the strategies must either be passed in or obtained in some other manner.

The only serious drawback I have found with the Strategy pattern is the number of additional classes I have to create. While well worth the cost, there are a few things I have done to minimize this when I have control of all of the strategies. In this situation, if I am using C++, I might have the abstract strategy header file contain all of the header files for the concrete strategies. I also have the abstract strategy cpp file contain the code for the concrete strategies. If I am using Java, I use inner classes in the abstract strategy class to contain all of the concrete strategies. I do not do this if I do not have control over all of the strategies; that is, if other programmers need to implement their own algorithms.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.221.113