Created
March 23, 2012 17:22
-
-
Save skhaz/2172956 to your computer and use it in GitHub Desktop.
Example of the MonoState pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/shared_ptr.hpp> | |
class VideoManagerPrivate { | |
private: | |
friend class VideoManager; | |
VideoManagerPrivate() { } | |
bool init(int _width, int _height, short _bpp, bool _fullscreen) { | |
width = _width; | |
height = _height; | |
bpp = _bpp; | |
fullscreen = _fullscreen; | |
return true; | |
} | |
int width; | |
int height; | |
short bpp; | |
bool fullscreen; | |
}; | |
class VideoManager { | |
public: | |
VideoManager() { } | |
VideoManager(int width, int height, short bpp, bool fullscreen) | |
{ | |
if (!init(width, height, bpp, fullscreen)) { | |
// throw ... | |
} | |
} | |
bool init(int width, int height, short bpp, bool fullscreen) | |
{ | |
if (!_manager) { | |
_manager.reset(new VideoManagerPrivate()); | |
} | |
return _manager->init(width, height, bpp, fullscreen); | |
} | |
int width() | |
{ | |
return _manager ? _manager->width : -1; | |
} | |
private: | |
static boost::shared_ptr<VideoManagerPrivate> _manager; | |
}; | |
boost::shared_ptr<VideoManagerPrivate> VideoManager::_manager; | |
int main(int argc, char **argv) { | |
// Em um dado momento, inicializa o video | |
{ | |
VideoManager video; | |
video.init(800, 600, 32, true); | |
} | |
// Em outro ponto do código, chama um método, como | |
// o objeto já foi inicializado, a saída será "800", caso contrario, -1 ou se | |
// preferir, uma exceção. | |
{ | |
using std::cout; | |
using std::endl; | |
VideoManager video; | |
cout << video.width() << endl; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment