Hey guys,
I want to clarify a doubt.
I’ve created and using my Singleton class in following manner.
Taken reference from Singleton
C++11 way of creating singleton instance.
GameManager.h
#ifndef LIB_CONTROLLER_GAMEMANAGER_H_
#define LIB_CONTROLLER_GAMEMANAGER_H_
class GameManager
{
public:
static GameManager* getInstance()
{
static GameManager *instance = new GameManager();
return instance;
}
// Game Play
int getGameScore();
void setGameScore(int latestScore);
private:
GameManager() {};
int gameScore = 1;
};
#endif /* LIB_CONTROLLER_GAMEMANAGER_H_ */
GameManager.cpp
#include "cocos2d.h"
#include "../Controller/GameManager.h"
USING_NS_CC;
int GameManager::getGameScore()
{
CCLog("\n\n\nGETTING GAME SCORE: %d\n\n\n", this->gameScore);
return this->gameScore;
}
void GameManager::setGameScore(int latestScore)
{
CCLog("\n\n\nSETTING GAME SCORE: %d\n\n\n", latestScore);
this->gameScore = latestScore;
}
Usage is like::: I’ve checked it by using in 2 different scenes and working fine.
GameManager::getInstance()->getGameScore();
GameManager::getInstance()->setGameScore(50);
1) That’s my entire code. I wanted to know, apart from this all above, what else do you add. I mean, is the above code all what I’ve to write and where I’ve to keep on adding functions, variables and keep on setting, getting them?
(I would be using CC_SYNTHESIZE(.., .., ..)
approach for writing getters and setters but that’s not the question)
2) How do you free memory memory when the cocos2d-x app is closed or when it is no longer neeeded? Also, I’ve not added deconstructor. I am not sure if following code must be added and called!
void GameManager::purge()
{
CC_SAFE_DELETE(this->getInstance());
}
3) Also, do you think, I should be using new (std::nothrow) GameMananger();
instead of new GameMananger();
to create the instnce?
Also, I understand the pros and cons of using Singleton and also that service locator seems to be a safe and good approach. But given the size of my game, I think I should use Singleton for now.
Purpose of my singleton would be simple:
Managing Game score struct, SDKBox stuffs if anything, theme settings, and userDefault for storing and retrieving data.
@Maxxx @smitpatel88 @slackmoehrle
Can someone plz have a look at it.
Thanks