cocos2d-x開発時にシングルトンにしたくなったときのメモ。
iOS(Objective-C)の場合
SingletonKero.h
1 2 3 4 |
@interface SingletonKero : NSObject + (SingletonKero *)getShared; @end |
SingletonKero.mm
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@implementation SingletonKero static SingletonKero *_instance = nullptr; + (SingletonKero *)getShared{ if (!_instance) { _instance = [SingletonKero new]; } return _instance; } @end |
インスタンスの取得
1 2 |
SingletonKero* shareInstance = [SingletonKero getShared]; |
cocos2d-x(C++)の場合
SingletonGiroro.h
1 2 3 4 5 6 |
class SingletonGiroro : public cocos2d::Ref { public: static SingletonGiroro *getShared(); }; |
SingletonGiroro.cpp
1 2 3 4 5 6 7 8 9 10 |
static SingletonGiroro *instance = NULL; SingletonGiroro *SingletonGiroro::getShared() { if (!instance) { instance = new SingletonGiroro(); } return instance; } |
インスタンスの取得
1 2 |
SingletonGiroro* shareInstance = SingletonGiroro::getShared(); |