Combining the Factory and Strategy Patterns

Download full source code.

I was recently talking with a friend about the factory and strategy patterns, how they could be used together. He was familiar with the factory, but not the strategy.

The factory lets you create the kind of object you want on the fly without explicitly calling new on a concrete class. The strategy pattern lets you execute some method defined in an interface without knowing which implementation is actually going to be used. These two patterns complement each other very well.

I gave the example of a messaging client that can send messages. Each message has some text content and a destination. All three need to be handled differently, especially voice, which would require some text to speech processing. The messaging client uses a factory to create the correct type of messaging service to send the message with. The factory looks at the message type to return the appropriate service - SMS, email, or voice, but only returns an interface (the strategy).

The messaging client is completely decoupled from the messaging services; it only knows about the messaging service interface, allowing new services to be added without needing to alter the client application.

The code is pretty simple to understand, so I won’t go through it here. Have a look at the full source code, which is attached.

Factory and Strategy
Factory and Strategy

Download full source code.

comments powered by Disqus