单例模式
1.饿汉模式:线程安全
public class HungryManSingleton { private static final HungryManSingleton instance = new HungryManSingleton(); private HungryManSingleton() { } public HungryManSingleton getIntance() { return instance; } }
2.懒汉模式:线程不安全
public class LazyManSingleton { private static LazyManSingleton instance = null; private LazyManSingleton(){} public LazyManSingleton getInstance(){ if(instance == null){ instance = new LazyManSingleton(); } return instance; } }
3.懒汉模式(线程锁):线程安全
public class LazyManSingleton { private volatile static LazyManSingleton instance = null; private LazyManSingleton(){} public synchronized LazyManSingleton getInstance(){ if(instance == null){ instance = new LazyManSingleton(); } return instance; } }
------------------------------------------------------------------------------
4.饿汉模式(强力推荐:并不是在;类加载的时候初始化对象,而是当调用的是时候才会初始化对象。节约资源):线程安全
public class HungerySingleton { private static class innerClass { private static final HungerySingleton instance = new HungerySingleton(); } private HungerySingleton() { } public static HungerySingleton getInstance() { return innerClass.instance; } }
本文来自博客园,作者:土木转行的人才,转载请注明原文链接