实现单例模式的8种方式
public class Singleton01 {
private static Singleton01 instance = new Singleton01();
private Singleton01(){
}
public static Singleton01 getInstance(){
return instance;
}
}
public class Singleton02 {
private static Singleton02 instance ;
static {
instance = new Singleton02();
}
private Singleton02(){
}
public static Singleton02 getInstance(){
return instance;
}
}
public class Singleton03 {
private static Singleton03 instance ;
private Singleton03(){
}
public static Singleton03 getInstance(){
if(null !=instance){
instance = new Singleton03();
}
return instance;
}
}
public class Singleton04 {
private static Singleton04 instance ;
private Singleton04(){
}
public static synchronized Singleton04 getInstance(){
if(null !=instance){
instance = new Singleton04();
}
return instance;
}
}
public class Singleton05 {
private static Singleton05 instance ;
private Singleton05(){
}
public static Singleton05 getInstance(){
if(null !=instance){
synchronized (Singleton05.class){
instance = new Singleton05();
}
}
return instance;
}
}
public class Singleton06 {
private static Singleton06 instance ;
private Singleton06(){
}
public static Singleton06 getInstance(){
if(null !=instance){
synchronized (Singleton06.class){
if(instance !=null){
instance = new Singleton06();
}
}
}
return instance;
}
}
public class Singleton07 {
private Singleton07(){
}
private static class SingletonInstance{
private static Singleton07 instance = new Singleton07();
}
public static Singleton07 getInstance() {
return SingletonInstance.instance;
}
}
public enum Singleton08 {
INSTANCE;
public void whateverMethod(){
}
}