Created
July 16, 2015 07:38
-
-
Save opoo/e48dbc0b3c5d0afddfc0 to your computer and use it in GitHub Desktop.
5 java singleton samples
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
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