设计模式-单例模式

创建型-单例模式

//单例模式 只允许实例化一个对象
//将构造函数私有

#include <iostream>
using namespace std;

class A{
private:
    A(){
        a = new A;
    }
public:
    static A* getInstace(){
        return a;
    }
private:
    static A* a;
};

A* A::a = NULL;


//实现单例步骤
//1.构造函数私有化
//2.增加静态私有的当前类的指针变量
//3.提供静态对外接口,可以让用户获得单例对象

//单例 分为懒汉式  饿汉式
//懒汉式
class Singleton_lazy{
private:
    Singleton_lazy(){ cout << "我是懒汉构造!" << endl;}

public:
        static Singleton_lazy* getInstance(){
            if(pSingleton == NULL){
                pSingleton = new Singleton_lazy;
            }
            return pSingleton;
        }
#if 0 //这样释放太危险
    static void freeSpace(){
        if(pSingleton != NULL){
            delete pSingleton;
        }
    }
#endif
    //如果非要写,可以加个类用来析构
    class Garbo{
        ~Garbo(){
            if(pSingleton != NULL){
            delete pSingleton;
        }
        }
    };

private:
    static Singleton_lazy* pSingleton;
    static Garbo garbo;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSingleton = NULL;

//饿汉式
class Singleton_hungry{
private:
    Singleton_hungry(){ cout << "我是饿汉式构造!" << endl;}

public:
    static Singleton_hungry* getInstance() {
		return pSingleton;
	}

private:
    static Singleton_hungry* pSingleton;
};
//类外初始化
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;

void test01(){

    Singleton_lazy* p1 = Singleton_lazy::getInstance();
    Singleton_lazy* p2 = Singleton_lazy::getInstance();
    if(p1 == p2){
        cout << "两个指针指向同一块内存空间,是单例!" << endl;
    }
    else{
        cout << "不是单例!" << endl;
    }

    Singleton_hungry* p3 = Singleton_hungry::getInstance();
    Singleton_hungry* p4 = Singleton_hungry::getInstance();
    if(p3 == p4){
        cout << "两个指针指向同一块内存空间,是单例!" << endl;
    }
    else{
        cout << "不是单例!" << endl;
    }
}

//单例对象释放问题
void test02(){
    //不用考虑内存泄漏问题
    //Singleton_lazy::freeSpace();
}

int main()
{
    //A a //A* a = new A;
    //A::getInstace();

    cout << "main函数开始执行" << endl;

    test01();

    system("pause");
    return 0;
}

//单例模式碰见多线程,懒汉式不安全,饿汉式安全

posted @ 2023-10-14 19:14  洋綮  阅读(4)  评论(0)    收藏  举报