Skip to content

Instantly share code, notes, and snippets.

@lamprosg
Last active December 15, 2015 01:39
Show Gist options
  • Select an option

  • Save lamprosg/5181061 to your computer and use it in GitHub Desktop.

Select an option

Save lamprosg/5181061 to your computer and use it in GitHub Desktop.
Singleton Class (C++/ Objectve-C)
class Singleton {
public:
static Singleton* getInstance(); //This will get us the singleton class instance
~Singleton();
private:
static Singleton* pInstance; //Flag if the instance already exists or not
//Constructot must be private
Singleton()
{
//private constructor
}
Singleton(const Singleton); // Prevent copy-construction
Singleton operator=(const Singleton); //Prevent assignment
};
//Initialize the static pInstance variable
Singleton* Singleton::pInstance = 0;
//Get our instane
Singleton* Singleton::getInstance() {
if (pInstance == 0) {
pInstance = new Singleton;
}
return pInstance;
}
----------------------------------------------
//USE IT
Singleton* object = Singleton::getInstance();
#import <foundation/Foundation.h>
@interface MyManager : NSObject
//Static function
+ (id)getInstance;
//Optionally make a custom constructor
-(void)initRequiredVariables;
//convenience declaration to get the singleton instance in the .h file
#define Manager [MyManager getInstance]
@end
#import "MyManager.h"
@implementation MyManager
#pragma mark - Singleton Methods
+ (id)getInstance {
//Static variable initialized once
static MyManager *pInstance = nil;
//The way we ensure that it’s only created once is by using the dispatch_once method from Grand Central Dispatch (GCD)
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
pInstance = [[self alloc] init];
});
return pInstance;
}
//Contructor
- (id)init {
if (self = [super init]) {
}
return self;
}
//Custom constructor
-(void)initRequiredVariables {
}
- (void)dealloc {
// Should never be called, but just here for clarity really.
}
@end
----------------------------------------------
//USE IT
MyManager *object = [MyManager getInstance];
//USE IT with the convenience declaration from the h file
Manager.someMemberMethodOrProperty
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment