我在我的程序中有几个模块(例如,数据库,调度程序),它们使用相同的实体-一些游戏服务器。
主要目标是每个模块使用具有有限功能的游戏服务器API (仅需要独立模块和游戏服务器之间交互的功能),其他功能必须隐藏。
我已经创建了这样的功能。但我现在不知道,也许这是错误的认识,或者是有人猜测更好的方法。
下面的类包含一些操作,这些操作只能通过类包装器从其他模块访问。
#ifndef _GAMESERVER_
#define _GAMESERVER_
#include <vector>
class GameServer
{
static GameServer instance;
std::vector<int> game_actions;
GameServer(){}
~GameServer(){}
GameServer(const GameServer&){}
protected:
void addGameAction(int action) // Some functionality, which can be accessible only from others modules via classes wrapers
{
game_actions.push_back(action);
}
public:
static GameServer *getInstance()
{
return &instance;
}
bool start()
{
return true;
}
void stop()
{
}
};
#endif下面放置了类GameServer的类'wrapper‘,它已经实现了与模块数据库交互的应用程序接口。
#ifndef _DBGAMESERVER_
#define _DBGAMESERVER_
/* Database module will use this API for interacting with game server */
class GameServer;
class DBGameServer : protected GameServer
{
DBGameServer();
public:
static DBGameServer *getInstance()
{
return static_cast<DBGameServer *>(GameServer::getInstance());
}
void addGameAction(int action)
{
GameServer::addGameAction(action);
}
};
#endif谢谢!
发布于 2015-01-15 19:25:58
您在第一次调用getIntance时创建了您的单例实例。这在多线程应用程序中可能是不安全的:争用条件可能导致实际初始化和使用多个实例。
我想你最好使用静态初始化:
声明:
...
class GameServer {
static GameServer& instance;
// private constructor, copie constructor and destructor
...
public:
static GameServer * getInstance() { return &instance; }
...
}实施:
...
GameServer & GameServer::instance = GameServer();
...这样你就可以确保对象在程序开始时(在第一条指令之前)只被构造一次,而析构函数在程序结束时(在最后一条指令之后)被调用。当然,如果构造器抛出一个异常,程序将在它有机会显示任何东西之前突然停止:最终的错误消息应该显示在构造器中。
https://stackoverflow.com/questions/27953431
复制相似问题