[英]Differences between two singleton examples
A级1级
public class A {
private static final A instance = new A();
public static A getInstance() {
return new A();
}
}
A 2级
public class A {
private static final A instance = new A();
private A(){}
public static A getInstance() {
return instance;
}
}
我刚刚开始学习单例,并且看到了两个Java示例,分别使用A 1类示例和A 2类示例。 A 1类getInstance()
是单例吗? 我还想知道这两个A类getInstance()
方法之间的区别是什么? 谢谢
我也想知道这两个A类getInstance()方法之间的区别
A类1:
如果您看一下代码:
public static A getInstance() {
return new A();
}
您在每次调用getInstance()
方法时都返回一个新的A
实例,因此它不是Singleton。 同样,在这种情况下,您没有将默认构造函数private
,并且您的类之外的任何代码都可以轻松创建打破Singleton范例的类的实例。
A类2:
看这段代码:
public class A {
private static final A instance = new A();
private A(){}
public static A getInstance() {
return instance;
}
}
您将为每次getInstance()
调用返回相同的实例。现在您的类的行为类似于Singleton,实际上您正在此处急切地实例化Singleton实例,并且此Singleton实例应该是线程安全的。 同时将课程定为final
课程, final
使任何人都无法对其进行子分类并破坏Singleton。
在第一种情况下
每次创建
A
的新实例时。
* 第二种情况*
按照单吨模式,应为
public class A {
private static A instance = null;
private A() {
}
public static A getInstance() {
if(instance == null) {
instance = new A();
}
return instance;
}
}
类
A
维护对单例实例的静态引用,并从静态getInstance()方法返回该引用。
A 1类getInstance()是单例吗?
否,因为每次调用此方法时,都会创建A
的新实例。
我还想知道这两个A类getInstance()方法之间的区别是什么?
第一个getInstance()
将始终创建类A的新实例,第二个getInstance()
将始终返回创建类A的相同实例。
There are two ways of creating a singleton class
1, Dynamic Singleton
2, Static Singleton
Static Singleton :
public class A {
//Create a object of class A and make it final so that nobody can modify it
private static final A instance = new A();
//make the constructor private so that new objects can not be created
private A(){}
//provide a method to access the object
public static A getInstance() {
return instance;
}
}
Dynamic Singleton :
a, Single Check
public class A {
//Create a object reference of class A
private static A instance = null;
//make the constructor private so that new objects can not be created
private A() {}
public static A getInstance() {
//check if instance is null or not
if(instance == null) {
if(instance == null) {
//if null then create an instance of class A and assign it to the final reference
instance = new A();
}
}
return instance;
}
}
b, double check
public class A {
//Create a object reference of class A
private static A instance = null;
//make the constructor private so that new objects can not be created
private A() {}
public static A getInstance() {
//check if instance is null or not
if(instance == null) {
synchronized(A.class){
//Double Check
if(instance == null) {
//if null then create an instance of class A and assign it to the final reference
instance = new A();
}
}
}
return instance;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.