单例模式

来源:互联网 发布:中科大软件学院考研 编辑:程序博客网 时间:2024/05/16 19:21

概念
单例模式是一种对象创建型模式,使用单例模式,可以保证为一个类只生成唯一的实例对象。也就是说,在整个程序空间中,该类只存在一个实例对象。

GoF对单例模式的定义是:保证一个类、只有一个实例存在,同时提供能对该实例加以访问的全局访问方法。

应用场合
1) 在多个线程之间,比如初始化一次socket资源;比如servlet环境,共享同一个资源或者操作同一个对象
2) 在整个程序空间使用全局变量,共享资源
3) 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。 因为Singleton模式可以保证为一个类只生成唯一的实例对象,所以这些情况,Singleton模式就派上用场了

实现步骤
a) 构造函数私有化
b) 提供一个全局的静态方法(全局访问点)
c) 在类中定义一个静态指针,指向本类的变量的静态变量指针

饿汉式单例和懒汉式单例

/*class Singelton {  //懒汉式    private static Singelton singel;    private Singelton() {}    public static synchronized Singelton getSingleton() { //每次调用这个方法都要同步,代价太大        if(singel == null)                                //而只是第一次才会出现不同步的问题            singel = new Singelton();        return singel;    } }*/class Singelton {  //懒汉式(双重检查)    private static Singelton singel;    private Singelton() {}    public static Singelton getSingleton() {        if(singel == null) {               synchronized(Singelton.class) {                if(singel == null)                     singel = new Singelton();            }        }        return singel;    } }class Signelton1 {  //饿汉式    private static Signelton1 signel = new Signelton1();    private Signelton1() {}    public static Signelton1 getSignelton1() {        return signel;    }}
#include <iostream>using namespace std;//懒汉式class  Singelton{private:    Singelton()    {        m_singer = NULL;        m_count = 0;        cout << "构造函数Singelton ... do" << endl;    }public:    static Singelton *getInstance()    {        if (m_singer == NULL )  //懒汉式:1 每次获取实例都要判断 2 多线程会有问题        {            m_singer = new Singelton;        }        return m_singer;    }    static void printT()    {        cout << "m_count: " << m_count << endl;    }private:    static Singelton *m_singer;    static int m_count;};Singelton *Singelton::m_singer = NULL;  //懒汉式 并没有创建单例对象int Singelton::m_count = 0;void main01_1(){    cout << "演示 懒汉式" << endl;    Singelton *p1 = Singelton::getInstance(); //只有在使用的时候,才去创建对象。    Singelton *p2 = Singelton::getInstance();    if (p1 != p2)    {        cout << "不是同一个对象" << endl;    }    else    {        cout << "是同一个对象" << endl;    }    p1->printT();    p2->printT();    system("pause");    return ;}//俄汉式class  Singelton2{private:    Singelton2()    {        m_singer = NULL;        m_count = 0;        cout << "构造函数Singelton ... do" << endl;    }public:    static Singelton2 *getInstance()    {//      if (m_singer == NULL )//      {//          m_singer = new Singelton2;//      }        return m_singer;    }    static void Singelton2::FreeInstance()    {        if (m_singer != NULL)        {            delete m_singer;            m_singer = NULL;            m_count = 0;        }    }    static void printT()    {        cout << "m_count: " << m_count << endl;    }private:    static Singelton2 *m_singer;    static int m_count;};Singelton2 *Singelton2::m_singer = new Singelton2; //不管创建不创建实例,均把实例new出来int Singelton2::m_count = 0;
0 0
原创粉丝点击