饿汉式:
public class Singleton{
private static Singleton instance= new Singleton ();
private Singleton (){
}
public Singleton getInstance(){
return instance;
}
}懒汉式:
public class Singleton{
private static Singleton instance= null;
public static getInstance(){
if(instance==null){
synchronized(Singleton.class){if(null == instance){
instance = new Singleton();
} }
}
return instance;
}
}
比较:
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的
推荐使用第一种