Tuesday, 29 April 2014

Observer Pattern

One of the Super patterns. This is the most used patterns in OOP. Coming to the real world, we deal with Observer pattern everyday. That greats masters of design patterns the GOF have such keen observation of of real world.

Here are some of the observers in real world. "Call me" and you leave your number. How many time did it happen that you left a Mobile number or a Business Card with someone. Many times you do get a call from places where you left your number. Isn't it?

Who is the observer in the above scenario? Well, observer is someone who is extremely eager to call you when he/she finds that something interesting has come up that may be of interest to you. Observer is always looking for opportunities to call because that the most important activity in his life.

The person who left the number with the Observer is not waiting for the call right? He is going about his business and doing the activities that are of his interest and important. Suddenly he gets a call from one of the places where he left his number :-). What must or will he do?

Well! generally, we look at the number and check if it is from a recognized source. If not, then based on the importance of the activity that we are performing at that time, we pickup or not pickup the call.

The beauty of the pattern is in the loose coupling between Observer and Subscriber. The Observer is performing his duty without knowledge or dependency on subscribers activities and same with subscribers.


 

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?