单例模式~
创始人
2024-12-28 16:37:02
0

概要

确保一个类只有一个实例,并提供一个全局访问点来访问该实例。

主要解决的问题

频繁创建和销毁全局使用的实例,减少开销。

解决思路

如果有该实例就返回,没有就创建。

应用场景

数据库连接池、线程池、spring中service等

几种实现方式

懒汉式 (多线程不安全)

实现简单

public class Singleton {     private static Singleton instance;     private Singleton(){}     private static Singleton getinstance(){         if(instance==null){             instance = new Singleton();         }         return instance;     } } 

懒汉式(多线程安全)

优点:第一次调用才初始化,避免内存浪费。
缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。

public class Singleton {     private static Singleton instance;     private Singleton(){}     private static synchronized Singleton getinstance(){         if(instance==null){             instance = new Singleton();         }         return instance;     } }

饿汉式(多线程安全)

优点:没有加锁,执行效率会提高。
缺点:类加载时就初始化,浪费内存。

public class Singleton {     private static Singleton singleton = new Singleton();     private Singleton(){}     public static Singleton getInstance(){         return singleton;     } } 

双重检查(线程安全)

public class Singleton {     private static volatile Singleton singleton;     private Singleton(){}     public static Singleton getInstance(){         if (singleton==null){             synchronized (Singleton.class){                 if (singleton==null){                     singleton = new Singleton();                 }             }         }         return singleton;     } } 

内部静态类(线程安全)

public class Singleton {     private static class SingletonHolder {         private static final Singleton INSTANCE = new Singleton();     }     private Singleton() {}     public static final Singleton getInstance() {         return SingletonHolder.INSTANCE;     } } 

枚举 

public enum SingletonTwo {     INSTANCE;     public void whateverMethod() {     } }

相关内容

热门资讯

WPK透视辅助!德州局脚本,w... WPK透视辅助!德州局脚本,wpk德州局透视(切实是有挂)1、超多福利:超高返利,海量正版游戏,wp...
微扑克透视辅助!pokemmo... 微扑克透视辅助!pokemmo辅助器手机版下载,hhpoker开挂教程(一贯是真的有挂)1、微扑克透...
WPK透视辅助!扑克之星辅助,... WPK透视辅助!扑克之星辅助,wepoker辅助是真的假的(真是真的有挂)wepoker辅助是真的假...
wpk透视辅助!hhpoker... wpk透视辅助!hhpoker是内部控制吗,wepoker破解工具(好像真的有挂)1、hhpoker...
微扑克透视辅助!hhpoker... 微扑克透视辅助!hhpoker德州透视,xpoker透视辅助(好像真的是有挂)1)hhpoker德州...
微扑克透视辅助!黑侠破解wep... 微扑克透视辅助!黑侠破解wepoker,wepoker辅助分析器(切实是有挂)1、首先打开wepok...
wpk透视辅助!aapoker... wpk透视辅助!aapoker怎么设置抽水,大菠萝手游辅助(总是真的有挂)运aapoker怎么设置抽...
wpk透视辅助!wepoker... wpk透视辅助!wepoker软件辅助程序,wepoker辅助器安装包定制(其实是有挂)小薇(辅助器...
微扑克透视辅助!aapoker... 微扑克透视辅助!aapoker怎么提高中牌率,hhpoker软件安装包(确实真的有挂)1、进入游戏-...
WPK透视辅助!wepoker... 您好,wepoker透视器免费这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054...