天天看點

單例模式

namespace 單例模式

{

class Student

int id;

string name;

//1

private Student()

}

//2

private static Student instance = new Student();

//3

public static Student Instance()

return

instance;

public int Id

get { return id; }

set { id = value; }

public string

Name

get { return name; }

set { name

= value; }

public void AttendClass()

Console.WriteLine("上課");

class Student2

private static Student2 instance ;

private Student2()

public static Student2 Instance()

if (instance ==

null)

instance = new Student2();

return instance;

public string Name

set { name = value;

namespace

單例模式

class Program

static void Main(string[]

args)

//Student zs = new Student();

//Student ls = new Student();

//bool b=zs.GetHashCode() ==

ls.GetHashCode();

Student zs = Student.Instance();

Student ls =

Student.Instance();

bool b = zs.GetHashCode() ==

Student2 zs2 = Student2.Instance();

Student2 ls2 =

Student2.Instance();

b = zs2.GetHashCode() ==

ls2.GetHashCode();