views:

129

answers:

2

Am familiar with the Head First book (in fact, thought it was brilliant), though sometimes it left me a bit confused with regard to patterns overlapping somewhat. But not really tried before to sit down and match a pattern from theory with a real world requirement.

Well, we now have a requirement for which I think we should be thinking in terms of patterns. Our client sells a bunch of products, all of which are highly configurable by his customers. For each sale we need to capture the customer's choice of width, height, colours, and a bunch of other technical stuff. Broadly the products are 80% similar in terms of all this data but they are different enough to make it complicated.

This feels like a "classic" requirement so that's why I am thinking patterns. Is it ... er .. strategy pattern? Or maybe decorator? If not, which pattern is it?

In case you need to know what we'll do with the customer's selections ... this will help to calculate cost price, affect commissions etc. These are operations which again are broadly going to work the same way for each product but may in some cases vary significantly from product to product.

We tried once before to implement this by simply subclassing the products and it got messy and that part of the project was abandoned. Our inept solution is described in the Head First book as an elementary mistake {blush} within about the first five pages.

+2  A: 

Sounds like the decorator pattern would serve well here.

And yes, I absolutely LOVED the Head First book. After reading that, GoF made complete sense to me.

Dinah
+1  A: 

If I understand the question correctly, you have 8 or 9 separate products, which I assume are individual classes in some kind of class hierarchy. Based on user-input, you need to apply certain additional logic to these classes like calculating cost price, affect commissions etc.

Since the latter is runtime behavior, using inheritance for this additional logic would indeed not be a very good idea as you would end up creating a number of almost identical subclass hierarchies beneath each product class.

I'm not sure if the additional functionality you mention needs to be accessed by the methods of the product classes themselves, but if so, a Decorator won't be a good fit as the object being wrapped by a Decorator is not aware it is being wrapped and can thus not call into its wrapper. If the additional behavior is only needed by the caller, a Decorator may be an option, but it still does not seem like a great fit to me.

The Strategy pattern seems match your problem much better. When the user selects a different way to calculate cost price for instance, you simply set a different Strategy implementation of ICostCalculator on the product object, thus making a runtime change to this particular aspect of the product's behavior. This seems to me to be exactly what you are looking for.

Luke Hutteman