Java设计模式: 单例模式
1.需要传递参数:
public class Singleton{ private volatile static Singleton instance = null; private int value = 0; private Singleton(){ value = 1024; } public static Singleton getInstance(Context context){ if (instance == null){ synchronized (Singleton.class){ if (instance == null){ instance = new Singleton(context.getApplicationContext()); } } } } }
2.不需要传递参数
public class Singleton{ private Singleton(){} public static Singleton getInstance(){ return SingletonHolder.instance; } private static class SingletonHolder{ private static final Singleton instance = new Singleton(); }
如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!欢迎各位转载,但是未经作者本人同意,转载文章之后必须在文章页面明显位置给出作者和原文连接,否则保留追究法律责任的权利。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步