Tuesday, July 24, 2007

singleton - the simpleton

hi,
In my last post, i spoke of design patterns and their importance.
now we can start discussing about the different design patterns and teh scenarios where we can use them.
i don't want to get into the details of separating the design patterns based on behavior ,creation etc.
we can just discuss the design patterns here.

the simplest of all the design patterns is "singleton".

lets consider this scenario. we are developing a game ( car race, of course). we have the car object.
but car object is a composite object which is composed of several other objects like wheels,steering,seat, window, brake,accelerator,clutch,gear etc.
steering is a class which looks like this

Interface Isteering
{
public void TurnLeft();
public void TurnRight();
}

public class Steering :ISteering
{
public Steering()
{

}

//we will haev to implement TurnLeft and TurnRight methods here
}

now steering will be called from the car class like this

steering CarSteer = new Steering();

but the flaw with this is that we can create the steering class even in the window class, as this would lead to two steering objects. one from the car and one from the window.
but we have a means to resolve this problem.

consider the code given below( i have modified the steering class)

public class Steering :ISteering
{
static _SteeringObject;

public static Steering GetSteering()
{
if(_SteeringObject == null)
{
_SteeringObject = new Steering();
}
return _SteeringObject;
}
private Steering()
{

}

//we will haev to implement TurnLeft and TurnRight methods here
}

and all the obejcts which want to access the steering object will cal the function like this

Steering objSteer = Steering.GetSteering();

the advantage of this is that there is a single instance of steering created and that instance will be accessed from any other class be it window or car class.

can we think of some other singleton patterns in the car class?

yes of course we can:

brake, accelerator,handbrake etc are all singletons.
we can discuss some other design pattern in my next post.

regards,
nandan

2 comments:

SANDIP ROY said...

okie... i would like to know why we use singleton pattern when just a static variable will serve our purpose...

even singleton implementation is impossible without static variable!!

ALSO DISPOING is doubtful for both???

which to use? which one is better,... and why??

nandan said...

we can do it with just a static variable-- yes.
but then we will have to check whether the static variable is null or not whenever we want the instance.

so putting it in the function will eliminate the need to check it.