html5中文学习网

您的位置: 首页 > 网络编程 > ASP.NET » 正文

Singleton Pattern in CSharp_.NET教程_编程技术

[ ] 已经帮助:人解决问题
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;
              }
}


33iHTML5中文学习网 - HTML5先行者学习网
33iHTML5中文学习网 - HTML5先行者学习网
(责任编辑:)
推荐书籍
推荐资讯
关于HTML5先行者 - 联系我们 - 广告服务 - 友情链接 - 网站地图 - 版权声明 - 人才招聘 - 帮助