Java:getInstance 与静态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24214148/
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
Java: getInstance vs Static
提问by FreakyDan
What is the purpose of getInstance()
in Java?
getInstance()
Java中的目的是什么?
During my research I keep reading that getInstance()
helps achieve a Singleton design pattern (which means just one instance across the whole program to my understanding). But can't I just use static? Isn't that the whole point of static?
在我的研究过程中,我一直在阅读getInstance()
有助于实现单例设计模式的文章(这意味着在我的理解中,整个程序中只有一个实例)。但是我不能只使用静态吗?这不是静态的全部意义吗?
If I were to just have static methods and fields, how would it differ from using getInstance()
? Is there a "scope" of static? For example, one instance per method or class?
如果我只有静态方法和字段,它与使用有getInstance()
什么不同?是否有静态的“范围”?例如,每个方法或类一个实例?
And if they are different, in what cases would I choose getInstance()
over using static?
如果它们不同,在什么情况下我会选择getInstance()
使用静态?
I apologize if the question is unclear, I am sure I am missing something on the subject matter, I just can't figure out what.
如果问题不清楚,我深表歉意,我确定我在主题上遗漏了一些东西,我只是不知道是什么。
Thank you for any and all advice.
感谢您的任何建议。
采纳答案by Zac Lozano
Static will not give you a singleton. Since there is no way of making a top-level class a singleton in Java, you have getInstance methods which will implement some logic to to be sure there is only one instance of a class.
静态不会给你一个单身人士。由于无法在 Java 中使顶级类成为单例,因此您可以使用 getInstance 方法来实现一些逻辑以确保类只有一个实例。
public class Singleton {
private static Singleton singleton;
private Singleton(){ }
public static synchronized Singleton getInstance( ) {
if (singleton == null)
singleton=new Singleton();
return singleton;
}
}
Check out this top answer: Static Classes In Java
查看此最佳答案:Java 中的静态类
The above code will allow only one instance to be created, and it's clean, however as of Java 1.6, it is better to create singleton's as such since it is slightly more elegant IMHO:
上面的代码只允许创建一个实例,而且它很干净,但是从 Java 1.6 开始,最好这样创建单例,因为它稍微优雅一点,恕我直言:
public enum MyEnumSingleton {
INSTANCE;
// other useful methods here
}
Source: http://www.vogella.com/tutorials/DesignPatternSingleton/article.html
来源:http: //www.vogella.com/tutorials/DesignPatternSingleton/article.html
回答by Victor2748
I prefer to use static
too, but sometimes getInstance()
is helpful to have some functions that will be related to the object, in which you can modify variables. if you are simply making some util functions that do not need an instance of an object, use static
.
我也更喜欢使用static
,但有时getInstance()
拥有一些与对象相关的函数会很有帮助,您可以在其中修改变量。如果您只是制作一些不需要对象实例的 util 函数,请使用static
.
When you are using someone's libraries, you never know if a function body needs a class instance. That's why a lot of library classes are using getInstance()
.
当您使用某人的库时,您永远不知道函数体是否需要类实例。这就是为什么很多库类都使用getInstance()
.
回答by Bohemian
The exact method of implementing a singleton, for example using a factory method called getInstance()
, isn't that relevant to the question, which is "static methods vs singleton with instance methods".
实现单例的确切方法,例如使用名为 的工厂方法getInstance()
,与问题无关,即“静态方法与具有实例方法的单例”。
Classes are themselves effectively singletons, so from that aspect they are similar.
类本身实际上是单例,因此从这方面来看它们是相似的。
The main difference is that static methods are not part of class hierarchy - they are not inherited, which means the static method option locks you forever to using that exact class and it can't be referred to in any other way, such being an implementation of some interface or a super class.
主要区别在于静态方法不是类层次结构的一部分 - 它们不是继承的,这意味着静态方法选项将您永远锁定为使用该确切类,并且不能以任何其他方式引用它,例如实现某些接口或超类。
Instances however don't have this problem, so you can code for example:
但是实例没有这个问题,所以你可以编码例如:
class MySingleton implements SomeInterface {
...
}
SomeInterface instance = MySingleton.getInstance();
回答by G.T.
Singleton
单身人士
A singleton allows you to use a single reference to a java Object. For example, here is a singleton which contains a number;
单例允许您使用对 java 对象的单个引用。例如,这是一个包含数字的单例;
public class MySingleton {
private int myNumber;
private static MySingleton instance;
public static MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
public void setMyNumber(int myNumber) {
this.myNumber = myNumber;
}
public int getMyNumber() {
return myNumber;
}
}
Now we are going to set the value of this number in the A class:
现在我们要在 A 类中设置这个数字的值:
public class A {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
mySingleton.setMyNumber(42);
/*...*/
}
Then, you can access this value from another class:
然后,您可以从另一个类访问此值:
public class B {
/*...*/
MySingleton mySingleton = MySingleton.getInstance();
int number = mySingleton.getMyNumber();
/*...*/
}
In this class the number
variable will have the value 42. This is the advantage of a singleton over a simple object:
在这个类中,number
变量的值为 42。这是单例相对于简单对象的优势:
All the values stored in the singleton will be accessible from "everywhere".
存储在单例中的所有值都可以从“任何地方”访问。
Static class
静态类
The purpose is different, here the advantage is to use an object without having to create it.
目的不同,这里的优点是使用对象而不必创建它。
For example:
例如:
public static class MyStaticClass {
public static void sayHello() {
System.out.println("Hello");
}
}
Now you can use the sayHello() method from any classes by calling:
现在,您可以通过调用以下命令来使用任何类中的 sayHello() 方法:
MyStaticClass.sayHello();
回答by Jason
Instead of checking for null, I like this a little better.
我更喜欢这个,而不是检查 null。
public class SingleObject {
//create an object of SingleObject
private static SingleObject instance = new SingleObject();
//make the constructor private so that this class cannot be
//instantiated
private SingleObject(){}
//Get the only object available
public static SingleObject getInstance(){
return instance;
}
}
Called with...
用...调用
public class SingletonPatternDemo {
public static void main(String[] args) {
//illegal construct
//Compile Time Error: The constructor SingleObject() is not visible
//SingleObject object = new SingleObject();
//Get the only object available
SingleObject object = SingleObject.getInstance();
}
}
Full code from: http://www.tutorialspoint.com/design_pattern/singleton_pattern.htm
完整代码来自:http: //www.tutorialspoint.com/design_pattern/singleton_pattern.htm
回答by William Deans
One overlooked reason to use a singleton instead of static class member variables is that the static member variables MAY use space and garbage collector time even in the event the class is never instantiated. Consider how many classes are available to you in rt.jar and what a small fraction of them you probably use in any given application. Also consider that using getInstance ensures your "constructor" has run before any of the member variables are accessed. I almost universally see getInstance as synchronized but I feel this is a bad idea. If anyone ever adds a synchronized blocking method calls to Singleton.getInstance().unsynchronized() could be needlessly held up.
使用单例而不是静态类成员变量的一个被忽视的原因是静态成员变量可能会使用空间和垃圾收集器时间,即使类从未被实例化。考虑在 rt.jar 中有多少类可供您使用,以及您可能在任何给定应用程序中使用其中的一小部分。还要考虑使用 getInstance 确保您的“构造函数”在访问任何成员变量之前已经运行。我几乎普遍认为 getInstance 是同步的,但我觉得这是一个坏主意。如果有人向 Singleton.getInstance().unsynchronized() 添加了同步阻塞方法调用,则可能会不必要地被阻止。
private static Singleton instance = null;
private Singleton() {}
public final static Singleton getInstance() {
return (instance != null) ? instance : makeInstance();
}
private final static synchronized Singleton makeInstance() {
return ( instance != null ) ? instance : ( instance = new Singleton() );
}