Java单例模式的四种写法
Posted 猿起
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java单例模式的四种写法相关的知识,希望对你有一定的参考价值。
1.饿汉式
public class DownLoad{
private static final DownLoad mDownload =new DownLoad();
private download(){
}
public static DownLoad getInstance(){
return mDownload ;
}
}
2.懒汉式
public class DownLoad{
private static final DownLoad mDownload ;
private download(){
}
public static DownLoad getInstance(){
if(mDownload ==null){
mDownload =new DownLoad();
}
return mDownload ;
}
}
3.double check(会出现空指针问题,可通过添加volatile关键字解决)
public class DownLoad{
private static volatile DownLoad mDownload ;
private download(){
}
public static DownLoad getInstance(){
if(mDownload ==null){
synchronized(DownLoad.class){
if(mDownload ){
mDownload =new DownLoad();
}
}
}
return mDownload ;
}
}
4.静态内部类
public class DownLoad{
public static class{
private static DownLoad mDownload=new DownLoad();
public static DownLoad getInstance(){
return mDownload;
}
}
}
以上是关于Java单例模式的四种写法的主要内容,如果未能解决你的问题,请参考以下文章