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 <stdio.h> | |
#include <stdlib.h> | |
typedef struct singleton{ | |
int id; | |
struct singleton* (*getInstance)(); | |
} Singleton; | |
static Singleton *instance; | |
Singleton *getInstance(){ | |
if(instance == NULL){ | |
instance = (Singleton *)malloc(sizeof(Singleton)); | |
} | |
return instance; | |
} | |
Singleton* createSingleton(){ | |
Singleton *instance = getInstance(); | |
instance->getInstance = getInstance; | |
return instance; | |
} | |
int main(){ | |
Singleton *s1 = createSingleton(); | |
Singleton *s2 = createSingleton(); | |
s1->getInstance()->id=10; | |
s2->getInstance()->id=20; | |
Singleton *obj = s1->getInstance(); | |
//if obj->id is 20, it may be singleton. | |
printf("%d",obj->id ); | |
} |
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
final class Singleton{ | |
private static Singleton instance; | |
private Singleton(){} | |
public static synchronized Singleton getInstance(){ | |
if(instance == null){ | |
instance = new Singleton(); | |
} | |
return instance; | |
} | |
} |
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
var Singleton = (function(){ | |
var instance; | |
function init(){ | |
return {} | |
} | |
return { | |
getInstance: function(){ | |
if(!instance){ | |
instance = init(); | |
} | |
return instance; | |
} | |
} | |
})(); |