----

Tuesday, September 3, 2013

Singleton Design Pattern Example

Singleton Design Pattern: This is the most simplest and most popular design pattern. This is a type of creational design pattern. This help us in creating a single object of a class.

Multiple objects can not be created as we do for any normal class shown here.

If we have a class A then we can say

A a1 = new A();// creates a new object of A
A a2 = new A();// creates a new object of A
A a3 = new A();// creates a new object of A

Each time a new object of class A will be created so a1, a2 and a3 will refer three different instances of class A. But the same is not possible with a singleton class.
You can not create an object of Singleton class using new operator.
  Singleton singleton = new Singleton();// is not possible, compile Time Error:
  //The constructor Singleton() is not visible


Sunday, September 1, 2013

Mediator Design Pattern Example

Mediator Design Pattern: Sometimes we need a mechanism to facilitate the interaction between objects in a manner in that objects are not aware of the existence of other objects. In other words Mediator helps in achieving loose coupling between various objects by keeping objects from referring to each other explicitly, and it makes their interaction independent.

There are some point which we need to keep in mind while choosing this design pattern.

  • Mediator pattern helps to achieve loose coupling.
  • You should know if there is a coupling between the components, in you code
  • Once you identified the coupling between the components, you can think of  using this design pattern.

I will explain it with example how you can decouple your various components from each other with help of a Mediator. Mediator provides us the freedom to do modification in any component without touching other components.

Lets take an example: You want to design a UI Screen which will have many components to display.