繁体中文
设为首页
加入收藏
当前位置:.Net技术首页 >> Asp.Net开发 >> Singleton Pattern in CSharp

Singleton Pattern in CSharp

2007-07-15 08:00:00  作者:  来源:互联网  浏览次数:0  文字大小:【】【】【
简介: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...
关键字:Singleton Pattern CSharp in

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;

}

}

责任编辑:admin
相关文章