手撕代码 单例模式 饿汉和懒汉

发布时间 2023-09-08 13:06:40作者: SuperTonyy
#include <bits/stdc++.h>
using namespace std;

class A {
private:
    static A* usr;
    static int cnt;
    A() {
        usr = NULL;
        cnt = 0;
        cout << "构造函数A" << endl;
    }
public:
    static A* get() {
        if (usr == NULL){
            usr = new A();
        }
        return usr;
    }
    static void print() {
        cout << "cnt = " << cnt << endl;
    }
};
A* A::usr = NULL;
int A::cnt = 0;

class B {
private:
    static B* usr;
    static int cnt;
    B() {
        usr = NULL;
        cnt = 0;
        cout << "构造函数B" << endl;
    }
public:
    static B* get() {
        return usr;
    }
    static void usrfree() {
        if (usr) {
            delete usr;
            usr = NULL;
            cnt = 0;
        }
    }
    static void print() {
        cout << "cnt = " << cnt << endl;
    }
};

B* B::usr = new B;
int B::cnt = 0;

int main()
{
    A* p1 = A::get();
    A* p2 = A::get();
    if (p1 == p2)
        cout << "p1和p2是同一个对象" << endl;
    else
        cout << "p1和p2不是同一个对象" << endl;
    p1->print();
    p2->print();

    B* p3 = B::get();
    B* p4 = B::get();
    if (p3 == p4)
        cout << "p3和p4是同一个对象" << endl;
    else
        cout<< "p3和p4不是同一个对象" << endl;
    p3->print();
    p4->print();
    B::usrfree();
    B::usrfree();

    system("pause");
    return 0;
}

A是懒汉类,B是饿汉类