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();


}

原文链接: https://www.cnblogs.com/buerdepepeqi/p/12713368.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ 中的单例模式

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342313

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午1:32
下一篇 2023年3月2日 上午1:32

相关推荐