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! :-)
It sounds like you may want A to be a Singleton.
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.
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
To elaborate on other answers:
And then call in B like this:
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:
then anywhere you can do
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.
Just use a static class and make sure it's public.