Saturday, 29 June 2013

The God object (patterns) [2]

In the previous post I was at a point where the baby was feeding, sleeping and most importantly making sure we spend money on nappies. In this post I attempt to extend my initial design.

So far my TheSpecialOne class looked like below:

A week went pass and after many hours of sleepless nights we realised that the baby was constantly hungry. Being responsible parents we kept on breast feeding, but it was time for the magic formula milk.

Our requirements were very simple. We wanted to be able to breast feed and swap to formula milk to top up. We wanted make this change without having to disturb the baby too much (or without him knowing).

If you take a step back, we see that feeding is an activity and only the method used for feeding is what is changing. So in reality we should be able to swap between different implementations (of feeding methods) without changing the abstraction. We would need the flexibility to alter the feeding process independent of the method used. Sounds familiar? What I am describing here is the Bridge pattern.

I have done some fundamental changes to my initial design. I introduced a new interface called IFeedStyle. This is the abstraction I will use to introduce different methods of feeding (e.g. bottle, spoon feed etc).
However I know that as he grows, we will need to be flexible. Consider the following code.

The key aspect here is that the "Start()" method is abstract. This way I can create as many derived classed as I want. As the baby grows his eating habits will change. While he is a baby, he may only take milk, but when he becomes a toddler some solid food. But while having solid food he may like to play with some toys but drink milk using a bottle. The idea is simple, based on different strategies, we can decide how to feed. For the moment we will only have a baby specific implementation of this abstract class.

The above abstract class must be integrated to the Person class. The following is the modified Person class.

I think you should see the advantage of using the Bridge pattern. The actual task of feeding does not change, only the implementation that meets the FeedableBase class. We can provide different implementation without modifying the Person class. Now the IFeedingStyle and FeedableBase can change independently.

All set, the calling code looks like this:

More to the point, the output looks like this.









Enough fun and back to real work!! (code is here)

No comments:

Post a Comment