namespace Organization
{
class Employee
{
// Cretae a static object of the class
private static Employee _employee = null;
private static object padlock = new object();
// This method will be called whenever an instance of the class will be needed
public static Employee GetInstance()
{
// Default constructor is specified as private, so that it coldnot be used from outside
private Employee()
{
}
}
}
{
class Employee
{
// Cretae a static object of the class
private static Employee _employee = null;
private static object padlock = new object();
// This method will be called whenever an instance of the class will be needed
public static Employee GetInstance()
{
lock(padlock)
{
if (_employee == null)
{
_employee = new Employee();
}
{
if (_employee == null)
{
_employee = new Employee();
}
}
return _employee
return _employee
}
// Default constructor is specified as private, so that it coldnot be used from outside
private Employee()
{
}
}
}
Hi you might find that another recommended way is the following
ReplyDeleteif (_employee == null)
{
lock(padlock)
{
if (_employee == null)
{
_employee = new Employee();
}
}
}
return _employee;
The reason is that locking mechanisms use resources and if the singleton is already initialized there is no need to utilize resources (Head First Design Patterns is a good place for reference)
Thanks...
ReplyDelete