Java: Using same instance of a class in various ot

2019-03-28 20:48发布

问题:

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.

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).

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.

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! :-)

回答1:

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.

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.



回答2:

To elaborate on other answers:

public class A
{
private static A instance;
private A()
{
    ...
}

public static A getInstance()
{
    if (instance == null)
        instance = new A();

    return instance;
}
...
public void doSomething()
{
    ... 
}
}

And then call in B like this:

A.getInstance().doSomething();


回答3:

It sounds like you may want A to be a Singleton.

In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object.

This means your existing code will have to modified to use some kind of getInstance() method, but once that change has been made all instances of class B will use a single instance of class A.

Here is a direct link to the: simplest example from the above site.



回答4:

Just use a static class and make sure it's public.



回答5:

Though you can use singleton design pattern to share the same instance every-time but if you want to use a same instance with parameters(overloaded constructor)..you cannot use SINGLETON