永发信息网

用C++实现单件模式,即设计一个类,该类仅允许被实例化一次。并举例说明单件模式的应用领域。

答案:2  悬赏:0  手机版
解决时间 2021-01-26 05:53
  • 提问者网友:我的未来我做主
  • 2021-01-25 18:18
用C++实现单件模式,即设计一个类,该类仅允许被实例化一次。并举例说明单件模式的应用领域。
最佳答案
  • 五星知识达人网友:刀戟声无边
  • 2021-01-25 19:09
C++单例模式也称为单件模式。使用单例模式,保证一个类仅有一个实例,并提供一个访问它的全局访问点。该实例被所有程序模块共享。有很多地方需要这样的功能模块,如系统的日志输出等。
单例模式有许多种实现方法,甚至可以直接用一个全局变量做到这一点,但这样的代码显得很不优雅。定义一个单例类,使用类的私有静态指针变量指向类的唯一实例,并用一个公有静态方法获取该实例。
#include 
using namespace std;

class Singleton
{
public:
    static Singleton* Instance();
    void SetValue(int value);
    int GetValue();
private:
    int* pVal_;
private:
    Singleton();
    ~Singleton();
    static Singleton* s_pInstance_;
};

Singleton* Singleton::Instance()
{
    if(NULL == s_pInstance_)
        s_pInstance_ = new Singleton;

    return s_pInstance_;
}

void Singleton::SetValue( int value )
{
    if(NULL == pVal_)
        pVal_ = new int;

    *pVal_ = value;
}

int Singleton::GetValue()
{
    if(NULL == pVal_)
        return 0;
    return *pVal_;
}

Singleton::Singleton():pVal_(NULL)
{
}

Singleton::~Singleton()
{
    if(NULL != pVal_)
        delete pVal_;
}

Singleton* Singleton::s_pInstance_ = NULL;

int main(int argc, char* argv[])
{
    Singleton* s = Singleton::Instance();
    s->SetValue(10);
    cout << s->GetValue() << endl;

    return 0;
}你可以在另外的类方法或者线程函数中直接使用Singleton类的公有方法Instance()得到单实例对象指针,可以看到这个指针值是一样的,这也就反映了单实例类的特性。
另外,以上的示例只有对单例类的实例化构造,但没有释放。不过这可以使用其他方式保证,如利用系统对静态对象的销毁机制实现一个守卫类,在守卫类的析构函数中进行单例类的释放。
全部回答
  • 1楼网友:廢物販賣機
  • 2021-01-25 19:54
static object a; static syncobject = new object(); public static object instance{     get {     lock(syncobject)     {     if(a ==null)     {     a = new object();     }     }     return a;     } }
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯