Skip to content

Instantly share code, notes, and snippets.

@ademar111190
Last active September 22, 2017 08:29
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ademar111190/de7c5fdc4a7ba29d8f5c to your computer and use it in GitHub Desktop.
Save ademar111190/de7c5fdc4a7ba29d8f5c to your computer and use it in GitHub Desktop.
One month with Kotlin: singleton example
// 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()
@SuigetsuSake
Copy link

public modifiers are the default modifiers in Kotlin so they are not mandatory

@zambral
Copy link

zambral commented Sep 22, 2017

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