1.
public class Singleton {
static Singleton instance = new Singleton();
private Singleton (){
}
public static Singleton getInstance() {
return instance;
}
2.
- public class Singleton {
- static Singleton instance;
- public static synchronized Singleton getInstance() {
- if (instance == null)
- instance == new Singleton();
- return instance;
- }
- }
-
- public class Singleton {
- static class SingletonHolder {
- static Singleton instance = new Singleton();
- }
- public static Singleton getInstance() {
- return SingletonHolder.instance;
- }
- }
本文介绍了三种不同的单例模式实现方式:饿汉式、懒汉式和静态内部类方式。通过这些示例,读者可以了解如何确保一个类只有一个实例,并提供一个全局访问点。
169

被折叠的 条评论
为什么被折叠?



