c++单例模式学习的第一天

看了Thinking in c++上的三个单例模式的例子,对它有了初步的理解。

先上代码:

例子1:

#include<iostream>
using namespace std;
class Singleton{
    static Singleton s;//创建私有静态实例(对象)step1
    int i;
    Singleton(int x):i(x){}
    Singleton& operator=(Singleton&);//disallowed不会被调用
    Singleton(const Singleton&);//disallowed不会被调用
public:
    static Singleton& instance(){return s;}//公有静态成员函数,调用s的唯一通道step2
    int getValue(){return i;}
    void setValue(int x){i=x;}
};

Singleton Singleton::s(47);//初始化,不初始化会报错
//cout<<&s<<endl;
int main()
{
    Singleton& s=Singleton::instance();
    cout<<s.getValue()<<endl;
    Singleton& s2=Singleton::instance();
    cout<<&s<<endl<<&s2<<endl;//地址相同,可见Singleton只有唯一一个实例
    s2.setValue(9);
    cout<<s.getValue()<<endl;
    return 0;

}


例子2:

#include<iostream>
#include<math.h>
using namespace std;
class Singleton
{
    int i;
    Singleton(int x):i(x){}
    void operator=(Singleton&);
    Singleton(const Singleton&);
public:
    static Singleton& instance(){
        static Singleton s(111);
        return s;
    }//在静态成员函数中创建静态实例,因为为static,所以在编译时就已经创建完成,不会因为多次调用函数创建多个对象
    int getValue(){return i;}
    void setValue(int x){i=x;}
};
int main()
{
    Singleton& s=Singleton::instance();
    cout<<s.getValue()<<endl;
    Singleton& s2=Singleton::instance();
    s2.setValue(9);
    cout<<s.getValue()<<endl;

}

例子3:

#include<iostream>
using namespace std;
template<class T>
class Singleton{
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);
    protected:
        Singleton(){}
        virtual~ Singleton(){}//虚析构函数,防止内存泄漏
    public:
        static T& instance(){
            static T theInstance;
            return theInstance;
        }
};
class MyClass:public Singleton<MyClass>{
    int x;
protected:
    friend class Singleton<MyClass>;
    MyClass(){x=0;}
public:
    void setValue(int n){x=n;}
    int getValue()const{return x;}
};
int main()
{
    MyClass& m=MyClass::instance();
    cout<<m.getValue()<<endl;
    m.setValue(1);
    cout<<m.getValue()<<endl;
}//相当于单件模板

https://blog.csdn.net/windboyzsj/article/details/2790485

//关于C++单件模式释放对象

https://www.cnblogs.com/cxjchen/p/3148582.html

//单例模式多线程

http://www.cnblogs.com/qicosmos/p/3145019.html

//单例模式模板化加进阶版




猜你喜欢

转载自blog.csdn.net/qq_37168920/article/details/80186444