The Singleton Pattern allows you to have only a single instance of an object of a particular class anywhere in the applicaiton.
The pattern will work in any class library or web services in the same application domain.
For example, if you have webService1 and webService2 and they are both in the same running application domain, you will see that both web services are accessing the same object instance.
class Program
{
static void Main(string[] args)
{
Robot a = Robot.Instance();
a.Name = "param";
Robot b = Robot.Instance();
Console.WriteLine("Robot's Name" + b.Name);
Robot c = Robot.Instance();
Console.WriteLine("Robot's Name" + c.Name);
Console.ReadKey();
}
}
//Singleton class
public class Robot
{
private static Robot self;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//hide the default constructor
private Robot() { }
public static Robot Instance()
{
//create instance only if we don't have one
if (self == null)
self = new Robot();
return self;
}
}
The pattern will work in any class library or web services in the same application domain.
For example, if you have webService1 and webService2 and they are both in the same running application domain, you will see that both web services are accessing the same object instance.
class Program
{
static void Main(string[] args)
{
Robot a = Robot.Instance();
a.Name = "param";
Robot b = Robot.Instance();
Console.WriteLine("Robot's Name" + b.Name);
Robot c = Robot.Instance();
Console.WriteLine("Robot's Name" + c.Name);
Console.ReadKey();
}
}
//Singleton class
public class Robot
{
private static Robot self;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//hide the default constructor
private Robot() { }
public static Robot Instance()
{
//create instance only if we don't have one
if (self == null)
self = new Robot();
return self;
}
}
No comments:
Post a Comment