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