单例模式常用方式

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;

    }

}

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容