C++ 单例模式

单例模式的意图:保证一个类只有一个实例,并提供一个访问它的全局访问点。
以下两种方法没有考虑线程安全问题,如需应用在多线程环境下,需要加锁。

第一种形式:实现通过返回一个引用实现单例模式。如果返回的是一个指针而不是一个引用,用户可能会不小心删除此指针,因此上述实现比返回指针更安全。'

class Singleton{
    static Singleton s;
    int i;
    Singleton(int x) : i(x){};
    Singleton & operator=(Singleton&); // 不允许赋值
    Singleton(const Singleton&); // 不允许拷贝
public:
    static Singleton& instance() {return s;}
    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;
    return 0;
}

第二种形式:通过成员函数内部的静态对象的创建实现单例模式。

class Singleton{
    int i;
    Singleton(int x) : i(x){};
    void operator=(Singleton&);
    Singleton(const Singleton&);
public:
    static Singleton & instance()
    {
        static Singleton s(47);
        return s;
    }
    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;
    return 0;
}
posted @ 2019-08-31 22:06  lllittletree  阅读(201)  评论(0编辑  收藏  举报