开发者

Java: Using same instance of a class in various other classes

开发者 https://www.devze.com 2023-04-13 01:26 出处:网络
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.

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 possib开发者_StackOverflow社区le 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! :-)


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.


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();


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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号