我的一位朋友向我展示了这是他对单例模式的实现。从我到目前为止的测试来看,这似乎很好。我不知道为什么,但是引用下面的“这个”对我来说似乎是错误的做法。
在构造函数中使用" this“是否合法?
public class Singleton {
private static Singleton unique = null;
private Singleton() { unique = this; }
public static Singleton instance() {
if (unique == null)
new Singleton();
return unique;
}
}
与通常的做法相比,这是否有显著的区别:
public class Singleton {
private static Singleton unique = null;
private Singleton() { }
public static Singleton instance() {
if (unique == null)
unique = new Singleton();
return unique;
}
}
我一直未能找到任何合理的答案来回答我的问题。
所以,提前谢谢!
发布于 2019-07-01 00:14:03
在构造函数中使用" this“是否合法?
这是可行的,但不合理,而且很难读懂。感觉更像是暗号味。
与通常的做法相比,甚至有显著的区别吗?
应始终考虑可读性和可维护性。将更难模拟和/或使用这个单例,因为它的实现是独一无二的。
此外,正如评论中所指出的。没有一个例子是线程安全的。意味着这不是真正的单身人士。
如果您想要一个具有延迟初始化的线程安全单例,我建议按以下方式实现它:
public class Singleton {
private static Singleton unique = null;
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (unique == null) {
unique = new Singleton();
}
return unique;
}
}
您可以通过引入双重检查锁定来增强它:
public static synchronized Singleton getInstance() {
if (unique == null) {
synchronized (Singleton.class) {
if (unique == null) {
unique = new Singleton();
}
}
}
return unique;
}
附加信息
有多种实现Singleton模式的方法:
https://www.geeksforgeeks.org/java-singleton-design-pattern-practices-examples/
https://stackoverflow.com/questions/56828452
复制相似问题