C++ 中的单例模式

C++ 中的单例模式

单例模式:一个类只有一个实例对象,C++一般的方法是将构造函数、拷贝构造函数以及赋值操作符函数声明为private级别,从而阻止用户实例化一个类。那么,如何才能获得该类的对象呢?这时,需要类提供一个public&static的方法,通过该方法获得这个类唯一的一个实例化对象。这就是单例模式基本的一个思想。

两种单例模式:

1.饿汉式:类产生时就创建好对象

2.饱汉式:需要的时候再创建对象

饿汉式

使用static修饰

#include<bits/stdc++.h>
using namespace std;
class A {
private:
    static A test;
    A() {
        cout << "单例模式创建" << endl;
    }
    A(const A &);
    A &operator = (const A &);
    ~A() {
        cout << "单例对象释放" << endl;
    }
public:
    static A *getInstance() {
        return &test;
    }
};
A A::test;
int main() {
    A *a1 = A::getInstance();
    A *a2 = A::getInstance();
    A *a3 = A::getInstance();
    A *a4 = A::getInstance();

}

智能指针版

#include<bits/stdc++.h>
using namespace std;
class A {
private:
    static shared_ptr<A> test;
    A() {
        cout << "单例模式创建" << endl;
    }
    A(const A &);
    A &operator = (const A &);
    ~A() {
        cout << "单例对象释放" << endl;
    }
    static void Des(A *) {
        cout << "销毁" << endl;
    }
public:
    static shared_ptr<A>  getInstance() {
        return test;
    }
};
shared_ptr<A> A::test(new A(), A::Des);
int main() {
    shared_ptr<A>a1 = A::getInstance();
    shared_ptr<A>a2 = A::getInstance();
    shared_ptr<A>a3 = A::getInstance();
    shared_ptr<A>a4 = A::getInstance();

}

饱汉模式

在调用的时候才创建对象

#include<bits/stdc++.h>
using namespace std;
class A {
private:
    A() {
        cout << "创建" << endl;
    };
    A(const A &);
    A &operator = (const A &);
    ~A() {
        cout << "销毁" << endl;
    };
public:
    static A *getInstance() {
        static A myInstance;
        return &myInstance;

    }
};
int main() {
    A *a1 = A::getInstance();
    A *a2 = A::getInstance();
    A *a3 = A::getInstance();


}

将对象创建在堆上的写法

#include<bits/stdc++.h>
using namespace std;
class A {
private:
    A() {
        cout << "创建" << endl;
    };
    A(const A &);
    A &operator = (const A &);
    ~A() {
        cout << "销毁" << endl;
    };
    static A *test;
public:
    static A *getInstance() {
        if(test == nullptr) {
            test = new A();
        }
        return test;
    }
private:
    class B {
    public:
        B() {};
        ~B() {
            if(test != nullptr) {
                delete test;
                test = nullptr;
            }
        }
    };
    static B b;
};
A *A::test = nullptr;
A::B  A::b;
int main() {
    A *a1 = A::getInstance();
    A *a2 = A::getInstance();
    A *a3 = A::getInstance();


}
posted @ 2020-04-16 15:49  buerdepepeqi  阅读(168)  评论(0编辑  收藏  举报