Saturday, April 3, 2010

The Singleton Pattern

The Singleton Pattern pattern is about there only being one instance of a particular type of object. This becomes handy if you need a class that'll be maintaining the state of some resource during the life-cycle of your application. In a non-singleton situation, let's say I have two instances of my ControllerClass running around, and I tell one of them to set_lights_to_blue(), so it sets the lights to blue and notes the change in state. But the other instance doesn't know about this blue-light state, and still thinks the lights are green. So now my code starts running in to all kinds of crazy errors.


You could solve this particular problem a number of ways. One is to have all ControllerClasses subscribe to each other in an Observer Pattern, or you could make set_lights_to_blue() be a static method, but if you really want to go OO and get all the inheritance and skip the observer overhead, then the Singleton Pattern is the way to go. The one *gotcha* here is that you need to do some thinking to make a singleton class thread safe, otherwise you may end up creating multiple instance of your class anyway and the previously-mentioned chaos ensues.

No comments: