我如何在Java中的不同类中使用相同的对象 [英] How can i use same object in different classes in Java
问题描述
假设我有3个java类A,B和C
Suppose i have 3 java classes A , B and C
我需要创建一个在A和B中都使用的C类对象但是问题在单独创建对象是类c的构造函数被调用2次。但是我想要只调用一次构造函数。
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类。
So i want to use the object created in class A into class b.
推荐答案
所以创建一次对象,并将其传递给A和B的构造函数:
So create the object once, and pass it into the constructors of A and 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;
}
}
请注意,这是非常在Java中常见的一种形式的依赖注入,这样就可以告诉对象他们的协作者而不是自己构建它们。
Note that this is very common in Java as a form of dependency injection such that objects are told about their collaborators rather than constructing them themselves.
这篇关于我如何在Java中的不同类中使用相同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!