单例模式(C++)

剑指offer 第二章面试的基础知识(2)

面试题2:实现Singleton模式(单例模式C++)
题目:设计一个类,我们只能生成该类的一个实例
1、方式一: 嵌套类 + 静态对象
#include 
#include 

using std::cout;
using std::cin;
using std::endl;

class Singleton
{
public:
    static Singleton* getInstance();
    //AutoRelease专为Singleton进行服务
    class AutoRelease
    {
    public:
        ~AutoRelease() {//在嵌套类内部可以直接访问外部类的静态数据成员
            if(_pInstance != nullptr) {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }
    };
    void init(int ix, int iy) {
        _ix = ix;
        _iy = iy;

    }

    void print() const {
        cout << "_ix=" << _ix << ","
             << "_iy=" << _iy << endl;
    }
    void p() const {
        printf("%p\n",_pInstance);
    }
private:
    int _ix,_iy;
    static Singleton* _pInstance;
    static AutoRelease _ar;//避免成为单例对象的一部分;设计成静态
    Singleton() {}
    Singleton(const Singleton&) = delete;//考虑复制
    Singleton& operator=(const Singleton&) = delete;//考虑赋值
};
//懒汉模式
//Singleton* Singleton::_pInstance = nullptr;
//Singleton::AutoRelease Singleton::_ar;
//
//Singleton* Singleton::getInstance() {
//    if(_pInstance == nullptr) {
//        return new Singleton();
//    }
//    return _pInstance;
//}

//饿汉模式
Singleton* Singleton::_pInstance = getInstance();//多线程安全问题
//在类之外进行初始化
Singleton::AutoRelease Singleton::_ar;
Singleton* Singleton::getInstance() {
    if(_pInstance == nullptr) {
    return new Singleton();
    }
    return _pInstance;
}

int main(void) {
    Singleton* p1 = Singleton::getInstance();
    
    p1->p();
    Singleton* p2 = Singleton::getInstance();
    p1->init(1,2);
    p1->print();
    p1->p();
    cout << p1 << endl;
    p2->init(4,7);
    p2->print();
    p2->p();
    cout << p2 << endl;
    return 0;
}

因为类内的成员函数为静态成员函数,所以类外也可以不用创建对象直接调用可以直接调用

执行结果

单例模式(C++)_第1张图片

去掉测试后代码版本

#include 
#include 

using std::cout;
using std::cin;
using std::endl;

class Singleton
{
public:
    static Singleton* getInstance();
    //AutoRelease专为Singleton进行服务
    class AutoRelease
    {
    public:
        ~AutoRelease() {//在嵌套类内部可以直接访问外部类的静态数据成员
            if(_pInstance != nullptr) {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }
    };
private:
    int _ix,_iy;
    static Singleton* _pInstance;
    static AutoRelease _ar;//避免成为单例对象的一部分;设计成静态
    Singleton() {}
    Singleton(const Singleton&) = delete;//考虑复制
    Singleton& operator=(const Singleton&) = delete;//考虑赋值
};
//懒汉模式
//Singleton* Singleton::_pInstance = nullptr;
//Singleton::AutoRelease Singleton::_ar;
//
//Singleton* Singleton::getInstance() {
//    if(_pInstance == nullptr) {
//        return new Singleton();
//    }
//    return _pInstance;
//}

//饿汉模式
Singleton* Singleton::_pInstance = getInstance();//多线程安全问题
//在类之外进行初始化
Singleton::AutoRelease Singleton::_ar;

Singleton* Singleton::getInstance() {
    if(_pInstance == nullptr) {
    return new Singleton();
    }
    return _pInstance;
}


2、方式二: 自动调用destroy方法,就可以回收单例对象
#include 
using std::cout;
using std::endl;

class Singleton
{
public:
	//在多线程环境下,并不能保证是线程安全的
	static Singleton * getInstance()
	{
		if(nullptr == _pInstance)
		{
			atexit(destroy);
			_pInstance = new Singleton();
		}
		return _pInstance;
	}

	static void destroy()
	{
		cout << "Singleton::destroy()" << endl;
		if(_pInstance) {
			delete _pInstance;
			_pInstance = nullptr;
		}
	}

	void init(int ix, int iy)
	{
		_ix = ix;
		_iy = iy;
	}

	void print() const
	{
		cout << "_ix: " << _ix << ","
			 << "_iy: " << _iy << endl;
	}
private:
	Singleton() {	cout << "Singleton()" << endl;	}
	~Singleton() {	
		cout << "~Singleton()" << endl;
	}

	Singleton(const Singleton&) = delete;
	Singleton & operator=(const Singleton&) = delete;

private:
	int _ix, _iy;
	static Singleton * _pInstance;
};

//饱汉模式(懒汉模式 -- 懒加载)
//Singleton * Singleton::_pInstance = nullptr;

//饿汉模式, 在进入main函数之前直接创建对象
Singleton * Singleton::_pInstance = getInstance();
 

void test0() 
{
	Singleton::getInstance()->init(1, 2);
	Singleton::getInstance()->print();
} 
 
int main(void)
{
	test0();
	return 0;
}

去掉测试后的版本

#include 
#include 

using std::cout;
using std::cin;
using std::endl;
//方式三: 自动调用destroy方法,就可以回收单例对象
class Singleton
{
public:
    static Singleton* getInstance();
    static void destroy() {
        cout << "Singleton::destroy()" << endl;
        if(_pInstance) {
            delete _pInstance;
            _pInstance = nullptr;
        }
    }

private:
    static Singleton* _pInstance;
    Singleton() {}
    Singleton(const Singleton&) = delete;//考虑复制
    Singleton& operator=(const Singleton&) = delete;//考虑赋值
};
//懒汉模式
Singleton* Singleton::_pInstance = nullptr;

//饿汉模式
//Singleton* Singleton::_pInstance = getInstance();//多线程安全问题
Singleton* Singleton::getInstance() {
    if(_pInstance == nullptr) {
        atexit(destroy);
        return new Singleton();
    }
    return _pInstance;
}

3、方式三: pthead_once + atexit,就可以回收单例对象(有环境限制,只能在linux环境下,实现了多线程安全)
#include 
#include 
#include 
using std::cout;
using std::cin;
using std::endl;

class Singleton
{
public:
    static Singleton* getInstance() {
        //pthread_once可以保证init_routine被执行一次
        pthread_once(&_once, init_routinue);
        return _pInstance;
    }

    static void destroy() {
            if(_pInstance != nullptr) {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }

    static void init_routinue() {
        _pInstance = new Singleton();
        atexit(destroy);
    }
    void init(int ix, int iy) {
        _ix = ix;
        _iy = iy;
    }


    void print() const {
        cout << _pInstance << endl
             << "ix = "    << _ix   << endl
             << "iy = "    << _iy   << endl 
             << endl ;
    }

private:
    int _ix,_iy;
    static Singleton* _pInstance;
    static pthread_once_t _once;
    Singleton(){}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

};
Singleton* Singleton::_pInstance = getInstance();
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;

void test0()
{
    Singleton* p1 = Singleton::getInstance();
    p1->init(1,2);
    p1->print();
    cout << p1;

    Singleton* p2 = Singleton::getInstance();
    p2->init(2,4);
    p2->print();
    cout << p2;


}


int main(void)
{
     test0();

     return 0;
}

执行结果

单例模式(C++)_第2张图片

去掉测试后的代码版本

#include 
#include 
#include 
using std::cout;
using std::cin;
using std::endl;

class Singleton
{
public:
    static Singleton* getInstance() {
        pthread_once(&_once, init_routinue);
        return _pInstance;
    }

    static void destroy() {
            if(_pInstance != nullptr) {
                delete _pInstance;
                _pInstance = nullptr;
            }
        }
    static void init_routinue() {
        _pInstance = new Singleton();
        atexit(destroy);
    }

private:
    int _ix,_iy;
    static Singleton* _pInstance;
    static pthread_once_t _once;
    Singleton(){}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};
Singleton* Singleton::_pInstance = getInstance();
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;

思维导图:

单例模式(C++)_第3张图片

未完待续

estroy);
}

private:
int _ix,_iy;
static Singleton* _pInstance;
static pthread_once_t _once;
Singleton(){}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
};
Singleton* Singleton::_pInstance = getInstance();
pthread_once_t Singleton::_once = PTHREAD_ONCE_INIT;


# 思维导图:

[外链图片转存中...(img-iRFlaQht-1669554518097)]

未完待续

### 需要思维导图或其他资料的小伙伴关注加私聊

你可能感兴趣的:(面试,单例模式,c++)