大豆

导航

C++设计模式-Singleton

意图:
保证一个类仅有一个实例,并提供一个访问他的全局访问点
适用:
当类只能有一个实例,而且客户可以从一个众所周知的的访问点访问它时
当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时
UML图:

解析:提供唯一的类的实例,但多线程下不一定安全
//test.h
//////////////////////////////////////////////////////////////////////////
class Singleton
{
public:
    Singleton()
{}
    
~Singleton(){}
    
    
//静态成员函数,提供全局的访问接口
    static Singleton* GetInstancePtr();
    
    
void test();
private:
    
//静态成员变量,提供全局的唯一实例
    static Singleton* m_pStatic;
}
;



// test.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
#include 
"stdlib.h"
#include 
"test.h"

using namespace std;
//////////////////////////////////////////////////////////////////////////
Singleton* Singleton::m_pStatic = NULL;

Singleton
* Singleton::GetInstancePtr()
{
    
if (NULL == m_pStatic)
    
{
        m_pStatic 
= new Singleton;
    }

    
return m_pStatic;
}


void Singleton::test()
{
    cout 
<< "test\n";
}

//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    
//直接通过全局访问点访问
    Singleton::GetInstancePtr()->test();
    
    system(
"pause");
    
return 0;
}

另一种与其相似的模式为monostate模式,将类中的所有数据声明为static即保持数据的状态唯一

posted on 2010-03-18 22:49  大豆  阅读(182)  评论(0)    收藏  举报