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


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值