Monday, 28 April 2014

Singleton Pattern

Most favorite and famous pattern. Here is a very simple real world analogy. A car is a composition of several objects. Any car has 4 Wheels, 2 vipers, 4 doors, multiple seats, etc.. Car also has objects such as Steering, Accelerator that exist only one in number.

You cannot imagine a car that has two steering wheels. This is a classic scenario that a software must represent in OOP. By definition, OOP must natively have facilities to represent single instance objects in a composition.

Singleton pattern is an effort to represent the real world single instance objects in a OOP programming language.

Interestingly, pattern can be looked at in few other angles. In the scenario of a car, there can be only one driver handling the steering wheel. The Singleton object steering wheel used by a Singleton user called a driver. Imagine situations where a Singleton object is being used by multiple Non-Singleton users. How do the OOP languages provide contention free access to the Singleton object?

Here is a scenario that is typical of a family setting. A family room has a TV. It has single remote control device to operate. What happens when few members of family are watching the TV? The Remote can be operated at any time by one of the members isn't it? What if all of them want to operate at the same time? Typical remote ends up broken?

How do OOPs allow us to depict the remote control scenario?

No comments:

Post a Comment