手写单例(饿汉式)
1 class SingleObj{ 2 //私有变量 3 private static SingleObj single=new SingleObj(); 4 //私有构造函数 不能被实例化 5 private static SingleObj(){} 6 7 public static SingleObj getInstance(){ 8 return single; 9 } 10 }
优点:没有加锁,执行效率更高
缺点:类加载时就初始化,浪费内存
懒汉式
1 class Singleton{ 2 private static Singleton single; 3 4 private static Singleton(){} 5 6 public static synchronized Singleton getInstance(){ 7 if(single==null) 8 single =new Singleton(); 9 return single; 10 } 11 }
优点:第一次调用才初始化,避免浪费内存
缺点:加锁了执行效率低