Skip to content

Instantly share code, notes, and snippets.

@md5555
Created March 7, 2014 06:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save md5555/9406266 to your computer and use it in GitHub Desktop.
Save md5555/9406266 to your computer and use it in GitHub Desktop.
Hidden Singleton (Java)
Hello Everyone,
Today a small tip from me, an extension of the singleton pattern that I call hidden singleton.
We all know the singleton:
public static class MySingleton {
private static MySingleton mInstance;
private final int x = 42;
private MySingleton() {
}
public static MySingleton getInstance() {
if( mInstance == null ) {
mInstance = new MySingleton();
}
return mInstance;
}
public int getX() {
return x;
}
}
OK, so if we want to get X, we write:
int myOwnX = MySingleton.getInstance().getX();
Ugly, right? Every time getInstance()? We can do better:
public static class MySingleton {
private static MySingleton mInstance;
private final int x = 42;
private MySingleton() {
}
private static MySingleton getInstance() { // Note how getInstance() is private now
if( mInstance == null ) {
mInstance = new MySingleton();
}
return mInstance;
}
public static int getX() { // Note how getX() is now static, too
return getInstance().x; // Ta-daaa, here's the magic
}
}
Now we can just write:
int myOwnX = MySingleton.getX();
Beautiful! (Well, at least a LITTLE bit nicer looking... ;-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment