Last active
September 22, 2017 08:29
-
-
Save ademar111190/de7c5fdc4a7ba29d8f5c to your computer and use it in GitHub Desktop.
One month with Kotlin: singleton example
This file contains hidden or 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
// Using Singleton on Kotlin | |
public object MySingleton { | |
public fun foo() { | |
} | |
} | |
// And use it on Kotlin | |
MySingleton.foo() | |
//------------------------------------------------------------------------------ | |
// Using Singletons in Java 7 | |
public class MySingleton { | |
private static MySingleton instance; | |
private MySingleton() { | |
} | |
public static MySingleton getInstance(){ | |
if(instance == null) { | |
instance = new MySingleton(); | |
} | |
return instance; | |
} | |
public void foo() { | |
} | |
} | |
//Using use it in Java | |
MySingleton.getInstance().foo() |
Hi,
your example in Java is not thread safe and so could be a no Singleton.
A better example could be
`
public class Singleton {
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
private SingletonHolder(){}
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}`
This way you don't use synchronise which break the performance and you use JVM static way of loading variables.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
public modifiers are the default modifiers in Kotlin so they are not mandatory