饿汉式
public class CustomerSingleton {
private static CustomerSingleton single = new CustomerSingleton();
private CustomerSingleton(){};
public static CustomerSingleton getInstance(){
return single;
}
懒汉式
public class Singleton{
private static Singleton instance = null;
private Singleton(){}
public static synchronized Singleton newInstance(){
if(null == instance){
instance = new Singleton();
}
return instance;
}
}
多线程内部类实现单例
public class InnerSingleton {
public static class Singletion{
private static Singletion single = new Singletion();
}
public static Singletion getSingletion(){
return Singletion.single;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Singletion single1 = InnerSingleton.getSingletion();
Singletion single2 = InnerSingleton.getSingletion();
System.out.println(single1 +"===="+ single2);
}
}
doubleSingleton
public class DubbleSingleton {
private static volatile DubbleSingleton ds;
public static DubbleSingleton getDs(){
if(ds == null){
synchronized (DubbleSingleton.class) {
if(ds == null){
ds = new DubbleSingleton();
}
}
}
return ds;
}