您的位置:首页 > 编程语言 > C#

C#设计模式_单例模式

2016-01-01 16:38 316 查看
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();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息