美文网首页
单例模式常用方式

单例模式常用方式

作者: 陈陈_04d0 | 来源:发表于2020-12-01 16:07 被阅读0次

    1、懒汉式  单线程方便,但是多线程不安全

    public class Test{

    public Test  test;

    public static Test  getInstance() {

        if (instance == null) { 

            test= new Test (); 

        } 

        return test; 

        } 

    }

    2、懒汉式 线程安全版

    public class Test{

        private static Test test; 

        public static synchronized Test getInstance() { 

        if (test== null) { 

            test = new Test(); 

        } 

        return test; 

        }  

    }

    3、饿汉式 线程安全,效率高,但是类创建就初始化对象,容易浪费内存

    public class Test{

    private static Test tes=new Test();

    public static synchronized Test getInstance() {

    return test;

        }  

    }

    4、双重验证方式  采用双锁机制,安全且在多线程情况下能保持高性能。

    public class Test {

    private static Testtest;

        public static TestgetSingleton() {

    if (test ==null)

    synchronized (Test.class) {

    if (test ==null)

    test =new Test();

       }

    return test;

        }

    }

    总结:一般优先选择第三种方式,特殊情况可以选择第四种。

    相关文章

      网友评论

          本文标题:单例模式常用方式

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