2017-09-04-单例模式

作者: 王元 | 来源:发表于2019-07-29 23:26 被阅读0次

    使用场景

    • 1.需要频繁实例化然后销毁的对象。
    • 2.创建对象时耗时过多或者耗资源过多,但又经常用到的对象。
    • 3.有状态的工具类对象。
    • 4.频繁访问数据库或文件的对象。

    1,恶汉式

    优点:简单易实现
    缺点:容易造成系统资源浪费。例如在实现数据库连接池,开始就创建暂时不使用的对象

    private static MyApp myApp = new MyApp();
    public static MyApp getInstance() {
        return myApp;
    }
    

    2,懒汉式:

    private static MyApp myApp = null;
    public static MyApp getInstance() {
        if(myApp == null) {
            myApp = new MyApp();
        }
        return myApp;
    }
    

    3,最优创建方式

    //上述的俩种方法在单线程的模式下是没有问题的。
    方法1:如果是多线程的模式下的话需要使用锁synchronized来避免多线程问题

    private static MyApp myApp = null;
    public static synchronized MyApp getInstance() {
        if(myApp == null) {
            myApp = new MyApp();
        }
        return myApp;
    }
    

    方法2:上述方法虽然可以避免多线的问题,但是由于对整个方法使用了synchronized,因此会造成性能问题

    private static MyApp myApp = null;
    public static MyApp getInstance() {
        if(myApp == null) {
            synchronized (myApp) {
                //这样做也是为了避免多线程环境下new出多个单例
                if(myApp == null) {
                    myApp = new MyApp();
                }
            }
        }
        return myApp;
    }
    

    4,使用枚举(不推荐):在effective java中介绍的一种,使用枚举实现单例。在Java中枚举天然实现了单例

    public enum  MyApp {
        INSTANCE;
        public static synchronized MyApp getInstance() {
            return INSTANCE;
        }
    }
    

    5,使用静态内部类(推荐)
    实现原理是利用了类加载机制,当类在第一次被使用的时候,虚拟机才会去加载类到内存,并初始化成员变量

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

    相关文章

      网友评论

        本文标题:2017-09-04-单例模式

        本文链接:https://www.haomeiwen.com/subject/ffswrctx.html