单例模式

1  单例模式下构建出来的对象本质上仍然是一个全局变量,因此全局变量可以完成同样的功能。

2  需要考虑线程安全,避免new出2个对象。

 

class SingleTon
{
private:
    int i_;
    SingleTon(int x) : i_(x) {}
    SingleTon &operator = (SingleTon &);
    SingleTon(const SingleTon &);        //not allow copy and assign
    ~SingleTon(){};
    static SingleTon *st_;
    static boost::mutex st_lock_;
public:
    static SingleTon *instance() 
    {
        boost::mutex::scoped_lock lock(st_lock_); //线程安全
        if (NULL == st_)
        {
            st_ = new SingleTon(47);
        }
        return st_;
    }
    int GetValue() {return i_;}
    void SetValue(int x) {i_ = x;}
};

boost::mutex SingleTon::st_lock_;
SingleTon * SingleTon::st_ = NULL;

int main()
{
    SingleTon *s = SingleTon::instance();
    std::cout << s->GetValue() << std::endl;
    SingleTon *s2 = SingleTon::instance();
    s2->SetValue(9);
    std::cout << s->GetValue() << std::endl;

    return 0;
}

 

 采用模板单件角方式实现。

//单件角实现方式 singleton-ness
template<class T>
class SingleTon
{
private:
    SingleTon &operator = (SingleTon &);
    SingleTon(const SingleTon &);       
protected:
    SingleTon() {}
    virtual ~SingleTon(){};
public:
    static T& instance() 
    {
        static T theInstance_;
        return theInstance_;
    }
};

class MyClass : public SingleTon<MyClass>
{
private:
    int x_;
protected:
    friend class SingleTon<MyClass>;
    MyClass() {x_ = 10;}
public:
    void SetValue(int n) {x_ = n;}
    int GetValue() const {return x_;}
};

int main()
{
    MyClass &m = MyClass::instance();

    std::cout << m.GetValue() << std::endl;
    m.SetValue(1);
    std::cout << m.GetValue() << std::endl;

    return 0;
}

 

posted @ 2013-09-23 09:15  calabashdad  阅读(181)  评论(0编辑  收藏  举报