设计模式之单例模式
单例模式:一个类只保留一个实例,通过私有化构造器,然后在本类中创建一个公共的静态的获取实例的方法,外部就可以通过类名.方法的形式获得该类的实例;
当多线程情况下,线程获得时间片短路,容易创建多个实例,所以采用一个锁机制解决。
public class Singleton { private static Singleton instance = new Singleton(); //先创对象 ,饿汉式 private Singleton() { } public static Singleton getInstance(){ return instance; } }
public class Singleton { private static Singleton instance=null; private Singleton() { } public static Singleton getInstance(){ if (instance == null) { instance = new Singleton(); //调用方法再创对象,懒汉式 } return instance; } }
为了应对多线程问题;采取一个加锁解决,把门关上,但是每次调用方法都会经过锁,会影响性能,所以在外面再加一个判断。
synchronized同步块括号中的锁定对象是采用的一个无关的Object类实例,而不是采用this,因为getInstance是一个静态方法,在它内部不能使用未静态的或者未实例的类对象,
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance(){ if (instance == null) { //外层一个判断,再进入锁 synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步