标签:return hung 私有 public == 有一个 get stat yun
顾名思义,单例模式就是要求只有一个实体对象。
单例模式分为懒汉式和饿汉式
饿汉式:一开始就创建对象,线程安全,但是如果用不到这个对象,会造成浪费
懒汉式:要的时候才创建,不会造成浪费,但是会有线程安全的问题.
饿汉式和懒汉式都是私有化构造函数,不让外面能够直接new 对象.
private static Hungry instance = new Hungry(); private Hungry(){} public Hungry getInstance(){ return instance; }
public class LazyUnSafe { private LazyUnSafe instance; public LazyUnSafe getInstance(){ if(instance == null){ instance = new LazyUnSafe(); } return instance; } }
public class LazySafe { private LazySafe instance; private LazySafe(){} public LazySafe getInstance() { if(instance == null){ synchronized (LazySafe.class){ if(instance == null){ instance = new LazySafe(); } return instance; } } return instance; } }
标签:return hung 私有 public == 有一个 get stat yun
原文地址:https://www.cnblogs.com/lzh66/p/13301236.html