Java:在各种其他类中使用类的相同实例 [英] Java: Using same instance of a class in various other classes

查看:23
本文介绍了Java:在各种其他类中使用类的相同实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是个愚蠢的问题,但我不知道答案,也不知道在哪里搜索答案,所以如果有人能帮助我就好了.

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.

我有一个具有不同成员和方法的类(让我们将其命名为 A).我在另一个类中使用了这个类的方法(我们将其命名为 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 a = new 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.

如果您真的想使用单例模式,请查看此处以获取 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆