我如何在 Java 的不同类中使用相同的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6762283/
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
How can i use same object in different classes in Java
提问by Vivek
Suppose i have 3 java classes A , B and C
假设我有 3 个 java 类 A , B 和 C
I need to create an object of class C that is used in both A and B but the problem in creating the object separately is that the constructor of class c is called 2 times. But i want the constructor to be called just once.
我需要创建一个在 A 和 B 中都使用的类 C 的对象,但单独创建对象的问题是类 c 的构造函数被调用了 2 次。但我希望构造函数只被调用一次。
So i want to use the object created in class A into class b.
所以我想使用在类A中创建的对象到类b中。
回答by Jon Skeet
So create the object once, and pass it into the constructors of A and B:
因此创建一次对象,并将其传递给 A 和 B 的构造函数:
C c = new C();
A a = new A(c);
B b = new B(c);
...
public class A
{
private final C c;
public A(C c)
{
this.c = c;
}
}
Note that this is verycommon in Java as a form of dependency injectionsuch that objects are told about their collaborators rather than constructing them themselves.
请注意,这在 Java 中作为依赖注入的一种形式非常普遍,这样对象就会被告知它们的合作者,而不是自己构造它们。
回答by Ryan Ische
Create object C outside of both A and B and have the constructors of A and B accept an instance of class C.
在 A 和 B 之外创建对象 C,并让 A 和 B 的构造函数接受类 C 的实例。
class A {
public A( C c ) {
....
}
}
class B {
public B( C c ) {
....
}
}
回答by Ben Page
Alternatively, if the constructors for A and B are not called near each other you could define Class c as a singleton. See http://mindprod.com/jgloss/singleton.html
或者,如果 A 和 B 的构造函数不是彼此靠近调用的,您可以将类 c 定义为单例。见http://mindprod.com/jgloss/singleton.html
you would then do:
然后你会这样做:
A a = new A(C.getInstance());
B b = new B(C.getInstance());
or alternatively, in constructors for A
and B
just call getInstance instead of the constructor, ie.
或者,在构造函数中A
,B
只调用 getInstance 而不是构造函数,即。
// C c = new C();
C c = C.getInstance();
回答by sblundy
You want to share an instance? Ok, how about his:
您想共享一个实例吗?好吧,他的:
C c = new C();
B b = new B(c);
A a = new A(c);
Another option is:
另一种选择是:
B b = new B();
A a = new A(b.c);