单例模式常用方式

2020-12-01  本文已影响0人  陈陈_04d0

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;

    }

}

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

上一篇下一篇

猜你喜欢

热点阅读