欢迎光临
我们一直在努力

Singleton Pattern in CSharp-.NET教程,C#语言

建站超值云服务器,限时71元/月

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 prints 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;
              }
}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » Singleton Pattern in CSharp-.NET教程,C#语言
分享到: 更多 (0)