Code
using System;
using System.Collections.Generic;
using System.Text;
namespace OODemo
{
/// <summary>
/// 饿汉式单例模式,在第一次加载时就实例化
/// </summary>
public class Singleton
{
private static readonly Singleton instance=new Singleton();
private Singleton()
{
}
public static Singleton GetInstance()
{
return instance;
}
}
/// <summary>
/// 懒汉式单例模式,在第一次被引用时开始实例化
/// </summary>
public class SingletonPattern
{
private static SingletonPattern instance;
private static object obj;
private SingletonPattern(){}
public static SingletonPattern GetInstance()
{
if (instance == null)
{
lock (obj)
{
if (instance == null)
{
return new SingletonPattern();
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
namespace OODemo
{
/// <summary>
/// 饿汉式单例模式,在第一次加载时就实例化
/// </summary>
public class Singleton
{
private static readonly Singleton instance=new Singleton();
private Singleton()
{
}
public static Singleton GetInstance()
{
return instance;
}
}
/// <summary>
/// 懒汉式单例模式,在第一次被引用时开始实例化
/// </summary>
public class SingletonPattern
{
private static SingletonPattern instance;
private static object obj;
private SingletonPattern(){}
public static SingletonPattern GetInstance()
{
if (instance == null)
{
lock (obj)
{
if (instance == null)
{
return new SingletonPattern();
}
}
}
}
}
}