Singleton Pattern in CSharp
2024-07-21 02:20:13
供稿:网友
注册会员,创建你的web开发资料库,singleton pattern in csharp
level author
beginner kunal cheda
singleton assures that there is one and only one instance of the class and provides a global point of access to it.there are number of cases in programming where you need to make sure that there can be one and only one instance of a class e.g window manager,print spooler etc.
points to note in the example constructor of class b is private not allowing other classes to create the instance. class b has a private static variable(x) which will have the one and one instance of the class b, and can be accessed through static method getb. if getb is accessed for the first time x will be null ,and will create the instance and return x, from next requests to getb method it will simply return x.
save the file as singleton.cs, compile c:/>csc singleton.cs and run c:/>singleton
code
singleton.cs
using system;
class a
{
public static void main(string [] args)
{
b m = b.getb();
m.j=100; //make changes to instance variable j
console.writeline(m.j);
b x = b.getb();
//x.j print's 100 which means that there is one and only one instance
console.writeline(x.j);
}
}
class b
{
private static b x;
public int j= 0;
private b()
{
}
public static b getb()
{
if(x==null)
{
x=new b();
}
return x;
}
}