国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發(fā) > 綜合 > 正文

Singleton Pattern in CSharp

2024-07-21 02:20:13
字體:
供稿:網(wǎng)友
注冊(cè)會(huì)員,創(chuàng)建你的web開發(fā)資料庫,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;
              }
}


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 慈溪市| 两当县| 玉山县| 海丰县| 北安市| 黑山县| 原阳县| 昭通市| 威远县| 青州市| 双辽市| 涿州市| 疏附县| 双鸭山市| 北流市| 三江| 丽江市| 平陆县| 大埔县| 育儿| 定日县| 芜湖县| 冕宁县| 南投县| 山阴县| 凤冈县| 石楼县| 伊春市| 沁阳市| 宁国市| 遵义县| 成都市| 西林县| 宁晋县| 罗山县| 山西省| 阿合奇县| 家居| 永宁县| 洞头县| 罗田县|