```cpp
#include<iostream>
using namespace std;
/*
实现单例的步骤:
1、构造函数私有化
2、增加静态私有的当前类的指针变量
3、提供静态的对外接口,可以让用户获得单例对象
*/
//单例:懒汉式
class Singleton_lazy {
private:
Singleton_lazy(){}
static Singleton_lazy* getInstance()
{
if (pSingleton==NULL)
{
pSingleton = new Singleton_lazy;
}
return pSingleton;
}
private:
static Singleton_lazy* pSingleton;
};
Singleton_lazy* Singleton_lazy::pSingleton = NULL;//类外初始化
//饿汉式
class Singleton_hungry {
private:
Singleton_hungry() {}
static Singleton_hungry* getInstance()
{
return pSingleton;
}
private:
static Singleton_hungry* pSingleton;
};
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;//类外初始化
int main()
{
system("pause");
return 0;
}
C#版
#region 懒汉单例模式
/// <summary>
/// 懒汉单例模式
/// </summary>
public class Singleton
{
//volatile 关键字 促进线程安全()
private static volatile Singleton mSingleton = null;
private static object Singleton_Lock = new object();
private Singleton() { }
public static Singleton CreateInstance()
{
//为再次创建对象服务 不用再排队了
if (mSingleton == null)
{
lock (Singleton_Lock)//保证只有一个线程进去判断 +初始化
{
if (mSingleton == null)
{
mSingleton = new Singleton();
}
}
}
return mSingleton;
}
}
#endregion
#region 饿汉式单例模式
/// <summary>
/// 饿汉式单例模式
/// </summary>
public class SingletonSecond
{
private static SingletonSecond mSingleton = null;
private SingletonSecond()
{
}
/// <summary>
/// 静态构造函数,由CLR保证 程序第一次使用这个类型前被调用 且只调用一次
/// </summary>
static SingletonSecond()
{
mSingleton = new SingletonSecond();
}
public static SingletonSecond CreateInstance()
{
return mSingleton;
}
/// <summary>
/// 原型模式 解决对象重复创建的问题
/// 通过MemberwiseClone 来clone新对象 避免重复创建
/// 原型模式:把对象的创建权限关闭,提供一个公开的静态的方法,提供全新的对象 不是走构造函数
///
/// </summary>
/// <returns></returns>
public static SingletonSecond CreateInstancePrototype()
{
SingletonSecond second = (SingletonSecond)mSingleton.MemberwiseClone();
return second;
}
}
#endregion
class Program
{
static void Main(string[] args)
{
Singleton_lazy p1 = Singleton_lazy.getInstance();
Singleton_lazy p2 = Singleton_lazy.getInstance();
if (p1==p2)
{
Console.WriteLine("p1=p2");
}
else
{
Console.WriteLine("p1!=p2");
}
Singleton_hungry p3 = Singleton_hungry.getInstance();
Singleton_hungry p4 = Singleton_hungry.getInstance();
if (p3 == p4)
{
Console.WriteLine("p3=p4");
}
else
{
Console.WriteLine("p3!=p4");
}
Console.ReadKey();
}
}
}