1、饿汉模式:
package com.abin.info.service;
public class Singleton {
private static Singleton singleton=new Singleton();
private Singleton(){
}
public static Singleton getInstance(){
return singleton;
}
}
private static LazyMode lazyMode=null;
public static synchronized LazyMode getInstance(){
if(null==lazyMode){
lazyMode=new LazyMode();
}
return lazyMode;
}
2、懒汉模式:
package com.abin.inter.she;
public class Singleton {
private static Singleton singleton=null;
private Singleton(){
}
public static Singleton getInstance(){
if(null==singleton){
return new Singleton();
}
return singleton;
}
}
懒汉模式的线程安全版本:
package com.abin.lee.template.pattern;
public class LazyMode {
private static LazyMode lazyMode=null;
public static synchronized LazyMode getInstance(){
if(null==lazyMode){
lazyMode=new LazyMode();
}
return lazyMode;
}
}
3、双重检测:
package com.east.abin.impl;
public class Singleton {
private static Singleton instance=null;
private Singleton(){
}
public static Singleton getInstance(){
if(null==instance){
synchronized(Singleton.class){
if(null==instance){
instance=new Singleton();
return instance;
}
}
}
return instance;
}
}
4.静态内部类:
单例模式创新!google的ioc作者写的。只有在调用的时候才会初始化!而且线程安全
超级牛!
package com.east.abin.bin;
public class Singleton {
private Singleton(){
}
private static class SingletonHelp{
private static Singleton instance=new Singleton();
}
public static Singleton getInstance(){
return SingletonHelp.instance;
}
}
5、enum类型的(这个是针对jdk 1.5以及1.5版本以上的)
package com.abin.peng.service;
public enum Singleton {
Singleton;
private Singleton(){}
public static Singleton getInstance(){
return Singleton;
}
}