java 只为一个类创建一个对象并重用相同的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14135459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create only one object for a class and reuse same object
提问by Ajay Gopal Shrestha
I want to create only one object of an class and reuse the same object over and over again. Is there any efficient way to do this.
我只想创建一个类的一个对象并一遍又一遍地重用同一个对象。有什么有效的方法可以做到这一点。
How can I do this?
我怎样才能做到这一点?
回答by Distortum
public final class MySingleton {
private static volatile MySingleton instance;
private MySingleton() {
// TODO: Initialize
// ...
}
/**
* Get the only instance of this class.
*
* @return the single instance.
*/
public static MySingleton getInstance() {
if (instance == null) {
synchronized (MySingleton.class) {
if (instance == null) {
instance = new MySingleton();
}
}
}
return instance;
}
}
回答by assylias
This is generally implemented with the Singleton patternbut the situations where it is actually required are quite rare and this is not an innocuous decision.
这通常是用单例模式实现的,但实际需要它的情况很少见,这不是一个无害的决定。
You should consider alternative solutionsbefore making a decision.
在做出决定之前,您应该考虑替代解决方案。
This other post about why static variables can be evilis also an interesting read (a singleton is a static variable).
关于为什么静态变量可能是邪恶的另一篇文章也是一个有趣的阅读(单例是静态变量)。
回答by Peter Lawrey
The simplest way to create a class with one one instance is to use an enum
创建具有一个实例的类的最简单方法是使用 enum
public enum Singleton {
INSTANCE
}
You can compare this with Steve Taylor's answer to see how much simple it is than alternatives.
您可以将其与史蒂夫泰勒的答案进行比较,看看它比替代方案简单得多。
BTW: I would only suggest you use stateless singletons. If you want stateful singletons you are better off using dependency injection.
顺便说一句:我只建议您使用无状态单例。如果你想要有状态的单例,你最好使用依赖注入。
回答by Anders R. Bystrup
That would be the Singleton pattern- basically you prevent construction with a private constructor and "get" the instance with a static synchronized getter that will create the single instance, if it doesn't exist already.
那将是单例模式- 基本上,您可以防止使用私有构造函数进行构造,并使用静态同步 getter 来“获取”实例,该实例将创建单个实例(如果它尚不存在)。
Cheers,
干杯,
回答by Dan D.
回答by giorashc
回答by Sean Patrick Floyd
You are looking for the Singleton pattern. Read the wikipedia article and you will find examples of how it can be implemented in Java.
您正在寻找单例模式。阅读维基百科文章,您将找到如何在 Java 中实现它的示例。
Perhaps you'd also care to learn more about Design Patterns, then I'd suggest you read the book "Head First Design Patterns"or the original Design Patterns bookby Erich Gamma et al (the former provides Java examples, the latter doesn't)
也许您还想了解更多有关设计模式的知识,那么我建议您阅读“Head First Design Patterns”一书或Erich Gamma 等人的原始设计模式书(前者提供了 Java 示例,后者没有) t)
回答by Jean Logeart
What you are looking for is the Singleton Pattern.
您正在寻找的是Singleton Pattern。