新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > .Net开发 > Asp.net教程 > 正文:Singleton Pattern in CSharp

Singleton Pattern in CSharp

新客网 XKER.COM 2003-07-12 来源: 收藏本文
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;
              }
}


收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐