Skip to content

Instantly share code, notes, and snippets.

@skhaz
Created March 23, 2012 17:22
Show Gist options
  • Save skhaz/2172956 to your computer and use it in GitHub Desktop.
Save skhaz/2172956 to your computer and use it in GitHub Desktop.
Example of the MonoState pattern
#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