Java的:在各种其他类使用类的同一个实例 [英] Java: Using same instance of a class in various other classes
问题描述
这可能是愚蠢的问题,但我不知道它的答案,我不知道到哪里去寻找答案,所以这将是很好,如果有人可以帮助我。
it might be stupid question, but I dont know the answer to it and I dont know where to search the answer, so it would be nice if someone could help me.
我有一个类(允许它的名称)不同的成员和方法。我用这个类的方法在另一个类(可以将其命名为B)。
I've a class (lets name it A) with different members and methods. I use the methods of this class in another class (lets name it B).
对于每一个B-对象创建我想用A的同一个实例这可能吗?
其实我在B中的构造函数,我称之为一个新= A();当然,我总是得到这个类的不同实例。
For every B-Object created I want to use the SAME instance of A. Is that possible? Actually I have a constructor in B where I call A a = new A(); Of course I always get different instances of this class.
我现在如何才能改变呢?我知道这可能是可能与Spring框架来解决它(注总是相同的对象变成B的实例),但我不能使用它。否则怎么会这样解决?
How can I now change this? I know it could be possible to solve it with spring framework (inject always the same object into the instances of B), but I cant use it. How else could this problem be solved?
非常感谢您的帮助! : - )
Thank you very much for your help! :-)
推荐答案
是其可能的。您需要定义CLASSA的单实例是静态的,并使用它,无论你想。
Yes its possible. You need to define a singleton instance of classA that is static, and use it wherever you want.
因此,有这样做的多种方式:
So there are multiple ways of doing this:
public class ClassA {
public static ClassA classAInstance = new ClassA();
}
那么任何地方,你可以做
then anywhere you can do
ClassA.classAInstance.whatever();
这是简单的,但也可能是够你。
This is simple, but it might be enough for you.
如果你真的想使用Singleton模式,看看这里一个Java的例子。这种方法的优点是,它可以确保你只有1 ClassA的实例。
If you really want to use the singleton pattern, look here for a Java example. The advantage of this approach is that it makes sure that you only have 1 classA instance.
这篇关于Java的:在各种其他类使用类的同一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!