Skip to content

Instantly share code, notes, and snippets.

@opoo
Created July 16, 2015 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save opoo/e48dbc0b3c5d0afddfc0 to your computer and use it in GitHub Desktop.
Save opoo/e48dbc0b3c5d0afddfc0 to your computer and use it in GitHub Desktop.
5 java singleton samples
public class SingletonDemo {
public static class Singleton1{
private static final Singleton1 instance = new Singleton1();
private Singleton1(){}
public static Singleton1 getInstance(){
return instance;
}
}
public static class Singleton2{
private static Singleton2 instance;
private Singleton2(){};
public static synchronized Singleton2 getInstance(){
if(instance == null){
instance = new Singleton2();
}
return instance;
}
}
public static class Singleton3{
private static volatile Singleton3 instance;
private Singleton3(){}
public static Singleton3 getInstance(){
if(instance == null){
synchronized (Singleton3.class){
if(instance == null){
instance = new Singleton3();
}
}
}
return instance;
}
}
public static class Singleton4{
private static final Singleton4 instance;
static{
instance = new Singleton4();
}
private Singleton4(){}
public static Singleton4 getInstance(){
return instance;
}
}
public static class Singleton5{
private static class SingletonHolder{
private static final Singleton5 instance = new Singleton5();
}
private Singleton5(){}
public static Singleton5 getInstance(){
return SingletonHolder.instance;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment