using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
namespace CShapeTest
{
// 没有考虑线程安全,如果有两个子线程在同时调用new方法时,会同时创建出两个Person对象
//class Person
//{
// private static Person m_instance = null;
// private Person() { }
// public static Person GetInstance()
// {
// if (m_instance == null)
// {
// m_instance = new Person();
// }
// return m_instance;
// }
//}
// 考虑线程安全,加上线程锁,保证不会两个线程同时调用new方法,从而达到只会创建一个Person对象
//class Person
//{
// private static Person m_instance = null;
// private static readonly object lockObject = new object();
// private Person() { }
// public static Person GetInstance()
// {
// if (m_instance == null)
// {
// lock(lockObject)
// {
// if (m_instance == null)
// {
// m_instance = new Person();
// }
// }
// }
// return m_instance;
// }
//}
// 使用C#的高级特性,可以减少书写单例模式的代码量
class Person
{
private static readonly Person m_instance = new Person();
private Person() { }
public static Person GetInstance()
{
return m_instance;
}
}
class Start
{
static void Main(string[] args)
{
var person = Person.GetInstance();
Console.WriteLine(person);
Console.ReadLine();
}
}
}
C#设计模式_单例模式
最新推荐文章于 2024-09-19 08:44:52 发布