Created
March 7, 2014 06:20
-
-
Save md5555/9406266 to your computer and use it in GitHub Desktop.
Hidden Singleton (Java)
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
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