java单例模式怎么实现

51次阅读
没有评论

共计 1060 个字符,预计需要花费 3 分钟才能阅读完成。

Java 中单例模式的实现方法有以下几种:

  1. 懒汉式(线程不安全):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {if (instance == null) {instance = new Singleton();
}
return instance;
}
}
  1. 懒汉式(线程安全):
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static synchronized Singleton getInstance() {if (instance == null) {instance = new Singleton();
}
return instance;
}
}
  1. 饿汉式:
public class Singleton {private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {return instance;}
}
  1. 双重检查锁定(Double-Checked Locking):
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();
}
}
}
return instance;
}
}
  1. 静态内部类:
public class Singleton {
private static class SingletonHolder {private static final Singleton INSTANCE = new Singleton();
}
private Singleton() {}
public static Singleton getInstance() {return SingletonHolder.INSTANCE;}
}

以上是几种常见的单例模式实现方法,每种方法都有各自的优缺点,可以根据具体需求选择适合的实现方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-12-21发表,共计1060字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)