ObjC & Swift & C++1x Singleton
//TheSingleton.h
@interface TheSingleton : NSObject
+(instancetype) sharedInstance;
+(instancetype) alloc __attribute__((unavailable("alloc not available, call sharedInstance instead")));
-(instancetype) init __attribute__((unavailable("init not available, call sharedInstance instead")));
+(instancetype) new __attribute__((unavailable("new not available, call sharedInstance instead")));
-(instancetype) copy __attribute__((unavailable("copy not available, call sharedInstance instead")));
@end
//TheSingleton.m
@implementation TheSingleton
+(instancetype) sharedInstance {
static dispatch_once_t pred;
static id shared = nil;
dispatch_once(&pred, ^{
shared = [[super alloc] initUniqueInstance];
});
return shared;
}
-(instancetype) initUniqueInstance {
id me = [super init];
// other initialize here.
return me;
}
@end
ObjC版使用:
TheSingleton* instance = [TheSingleton sharedInstance];
swift 版:
class TheSingleton {
class var sharedInstance : TheSingleton {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : TheSingleton? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = TheSingleton()
}
return Static.instance!
}
}
或者:
class TheSingleton {
class var sharedInstance : TheSingleton {
struct Static {
static let instance : TheSingleton = TheSingleton()
}
return Static.instance
}
}
swift版使用:
let instance = TheSingleton.sharedInstance
C++1x Singleton,下面的方法已经过时了,其实C++11有更简单的实现方式:
#ifndef SINGLETON_H
#define SINGLETON_H
#include <mutex>
#include <functional>
#include <memory>
#include <utility>
template<class SingleClass>
class Singleton
{
public:
Singleton() = default;
virtual ~Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
template<typename IMPL = SingleClass, typename... Args>
static SingleClass& instance(Args&&... args)
{
std::call_once(get_once_flag(), [](Args && ... arg) {
_instance.reset(new IMPL(std::forward<Args>(arg)...));
}, std::forward<Args>(args)...);
return *(_instance.get());
};
private:
static std::unique_ptr<SingleClass> _instance;
static std::once_flag& get_once_flag() {
static std::once_flag once;
return once;
};
};
template<class T> std::unique_ptr<T> Singleton<T>::_instance = nullptr;
#endif