Java: Using same instance of a class in various other classes - 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.
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! :-)

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

Related

create 2 instances of a singleton class Java

I know this question is weird but just wondering: is there any way to create multiple instances of a Singleton class in Java?
My situation is like this:
I have an Singleton class and i need to have 2 objects/instances of that class. Is there any way to modify class to be able to create multiple instances?
My class:
public class SingletonClass {
private static SingletonClass sSoleInstance;
//private constructor.
private SingletonClass(){
//Prevent form the reflection api.
if (sSoleInstance != null){
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static SingletonClass getInstance(){
if (sSoleInstance == null){ //if there is no instance available... create new one
sSoleInstance = new SingletonClass();
}
return sSoleInstance;
}
}
One can use the enum pattern to create singletons; like
public enum Whatever {
INSTANCE;
}
Turning that into a Bi-Singleton goes like:
public enum Whatever {
INSTANCE, YETANOTHER
}
For the record: I just made up the word "bi-singleton"; simply as this makes close to 0 sense from a conceptual point of view. If you need more than one instance, it is not a singleton; period. So your question sounds more like an XY problem.
And just a note: consider using that enum solution; as it is thread safe by default; the code you are using is not. But before making changes, do a bit of research to understand the pros and cons of those approaches.
Absolutely valid question with a valid use case - in a nutshell you can have multiple instances of a class with a private constructor when employing static factory methods. You ensure that your class cannot be instantiated from the outside world by making the constructor private, but at the same the class in question can instantiate itself as many times as it pleases.
Check this article for details and code samples.
Hope that helps.

java, as flliows,why does this global varaible of the program keep only an instance?

Could the uniqueeInstance have one and only one instance?
public class A {
private static A uniqueInstance = new A();
private A() {}
public static A getInstance() {
return uniqueInstance;
}
}
This is a Singleton pattern, it's purpose is to have only one possible instance for a class.
This is why you have a private constructor , so that no other class can attempt to instantiate it directly.
Here are more elaborate thoughts for possible uses of a Singleton :
When to use the Singleton
It is not guaranteed.
By reflection you are easy to get more instances.
The only way to guarantee that you have exactly one instance is to use an enum:
enum Holder {
INSTANCE;
//Keep in Mind of A you may still have more instances. if you want to have the
//guarantee to have only one instance you may need merge the whole class
//into an enum (which may not be possible)
public A uniqueInstance = new A();
}
Other ways like throwing an exception in the constructor are generally also possible. But not completely secure since there are ways to create an Object without calling any constructor.

How should i implement an interface in Java? [Code-Correctness]

First of all this is not a question about how to implement an interface in Java, or about an error with interfaces. This is a question about the right way to do it, depending on the situation.
First of all i would like to apologize if this is not the correct "stack" to post this question, please let me know and i'll move it to another one.
Let's begin.
What i'm trying to guess is which is the best way to implement an interface in Java. Let's say we have a class A like:
public Class A {
public A(){}
public void fooA() {}
}
And an interface
public interface MyListener {
public void fooListener();
}
Inside fooA() I'm making use of interface B this way:
...
something.setFooListener(/**Doubts here**/)
....
What should we type inside setFooListener(...)
Options are (As far as i know):
A) Define the behavior inside the setFooListener function:
new MyListener.fooListener() {
/** Implementation of fooListener() **/
}
Pros:
Easy and readable as you're reading the function.
You can access directly to FINAL variables defined in fooA().
Cons:
If your implementation is long enough it would end up in a lack of readability and a too long function.
If you're implementing the interface in a few places on the same class you are going to repeat a lot of code.
B) Create an inner class implementing the interface:
private class MyListenerImplementation implements MyListener {
private String var1;
private int var2;
public MyListenerImplementation() {/** constructor **/}
public void fooListener() {
/** Do logic here **/
}
}
Pros:
You can keep a reference to the object MyListenerImplementation.
You can define variables, functions and everything as it's an object like any other one.
Cleaner code.
Cons:
Maybe needs more memory.
Maybe creating unnecessary classes
C) Hold a variable with a reference to the interface implementation
private MyListener.FooListener myListenerVar = new MyListener.FooListener() {
/** Logic goes here **/
};
Pros:
I actually can't sees anyone comparing to B, but a lot of cons.
Cons:
Not a clean code. Doing this on top of your class would be, at least, a war crime.
I don't think it's correct to assign a block of code to a variable.
I don't like how this looks ;)
D) The last one i could think of; define a function and inside return the implementation
private MyListener.fooListener createMyListener() {
return new MyListener.fooListener() {
/** Logic goes here **/
}
}
Pros:
It's cleaner than C.
Reusability
Cons:
Almost the same ones as C.
I don't think it's correct to return a whole block of code.
To sum up: Which i like the most is "B", but i would like to know what does SO thinks of this.
Thanks in advice.
Option A is not syntaxically correct. Your pros and cons are valid.
Option B:
Maybe needs more memory: no.
Maybe creating unnecessary classes: no. Option A also creates a class. It's anonymous, but it's a class, that must be loaded by the ClassLoader like any other class.
Option C: it's exactly the same as A (anonymous class usage), except you initialize a field with the listener. The rule is the same as for any other variable: reduce its scope as much as possible. If you need a field scope, use this option. If you only need the listener in one method, then use a local variable (option A).
Option D: once again, it's the same as A, except you return the created listener instead of only using it.
My recap: you're mixing three orthogonal problems here.
Should I use an anonymous inner class, a named nested class, or a top-level class. This depends on the amount of code contained in the class, and on where you need to use this class: in a single top-level class, or in many top-level classes.
Should I use local variables or instance variables. it's a matter of scope and state, not a matter of interface implementations. Your field or local variable can be initialized with an instance of any kind of your interface implementation
Should you use a factory method returning instances, or should you use new directly. Once again, that has nothing to do with how your interface is implemented. If you want to be loosely coupled, because the factory method might return different implementations of the same interface, use a factory. Otherwise, new is fine.

Singleton Pattern

This question, like my previous question, references Effective Java. This time I have quite a few sub-questions.
A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible() method. If you need to defend against this, modify the constructor.
How, exactly, can a private constructor be invoked? And what is AccessibleObject.setAccessible()?
What approach do you experts follow with singletons?
// Approach A
public class Test{
public static final Test TestInstance = new Test();
private Test(){ ... }
.
.
.
}
// Approach B
public class Test{
private static final Test TestInstance = new Test();
private Test(){ ... }
public static Test getInstance() { return TestInstance; }
.
.
.
}
Isn't the second approach more flexible, in case we have to make a check for new instances every time or the same instance every time?
What if I try to clone the class/object?
a single-element enum type is the best way to implement a singleton.
Why? How?
A priviledged cleint can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method, If you need to defend this, modify the constructor. My question is: How exactly can a private constructor is invoked? and what is AccessibleObject.setAccessible??
Obviously a private constructor can be invoked by the class itself (e.g. from a static factory method). Reflectively, what Bloch is talking about is this:
import java.lang.reflect.Constructor;
public class PrivateInvoker {
public static void main(String[] args) throws Exception{
//compile error
// Private p = new Private();
//works fine
Constructor<?> con = Private.class.getDeclaredConstructors()[0];
con.setAccessible(true);
Private p = (Private) con.newInstance();
}
}
class Private {
private Private() {
System.out.println("Hello!");
}
}
2.What approach do you experts follow with singletons:
...
Typically, the first is favoured. The second (assuming you were to test if TestInstance is null before returning a new instance) gains lazy-loading at the cost of needing to be synchronized or being thread-unsafe.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, the above consideration is irrelevant.
Isn't the second approach more flexible in case we have to make a check for new instance every time or same instance every time?
It's not about flexibility, it's about when the cost of creating the one (and only) instance is incurred. If you do option a) it's incurred at class loading time. That's typically fine since the class is only loaded once it's needed anyway.
I wrote the above when your second example didn't assign the instance to TestInstance at declaration. As stated now, in both cases the Singleton will be created at class load.
What if I try to clone the class/object?
A singleton should not allow cloning for obvious reasons. A CloneNotSupportedException should be thrown, and will be automatically unless you for some reason implement Cloneable.
a single-element enum type is the best way to implement a singleton. Why? and How?
Examples for this are in the book, as are justifications. What part didn't you understand?
Singletons are a good pattern to learn, especially as an introductory design pattern. Beware, however, that they often end up being one of the most over-used patterns. It's gotten to the point that some consider them an "anti-pattern". The best advice is to "use them wisely."
For a great introduction to this, and many other useful patterns (personally, I find Strategy, Observer, and Command to be far more useful than Singleton), check out Head First Design Patterns.
A priviledged cleint can invoke the private constructor reflectively with
the aid of the
AccessibleObject.setAccessible method,
If you need to defend this, modify the
constructor. My question is: How
exactly can a private constructor is
invoked? and what is
AccessibleObject.setAccessible??
You can use java reflection to call private constructors.
What approach do you experts follow with singletons:
I am a fan of using enum to actually do this. This is in the book also. If that's not an option, it is much simpler to do option a because you don't have to check or worry about instance being already created.
What if I try to clone the
class/object?
Not sure what you mean? do you mean clone() or something else that I don't know of?
a single-element enum type is the best way to implement a singleton.
Why? and How?
Ahh my own answer. haha. This is the best way because in this case, the java programming language guarantees a singleton instead of the developer having to check for a singleton. It's almost as if the singleton was part of the framework/language.
Edit:
I didn't see that it was a getter before. Updating my answer to this - it's better to use a function such getInstance because you can control what happens through a getter but you can't do the same if everybody is using a reference directly instead. Think of the future. If you ended up doing SomeClass.INTANCE and then later you wanted to make it lazy so it doesn't load right away then you would need change this everywhere that its being used.
The first rule of the Singleton (Anti-) Pattern is don't use it. The second rule is don't use it for the purpose of making it easy to get at a single instance of a class that you want multiple other objects to share, especially if it is a dependency of those classes. Use dependency injection instead. There are valid uses for Singletons, but people have a tendenecy to badly misuse them because they're so "easy" to use. They make it very difficult to test classes that depend on them and make systems inflexible.
As far as your questions, I think 1, 2 and 3 can all be answered by saying "use an enum-singleton". Then you don't need to worry about constructor accessiblity issues, clone()ing, etc. As far as 4, the above is a good argument for them. I also have to ask, did you read the section in Effective Java that explicitly answers your question?
Example singleton lazy init:
Class main:
public class Main {
public static void main(String[] args) {
System.out.println(Singleton.getInstance("first").value);
System.out.println(Singleton.getInstance("second").value);
System.out.println(Singleton.getInstance("therd").value);
}
}
Class singleton:
public class Singleton {
private static Singleton instance;
public String value;
private Singleton (String s){
this.value =s;
}
public static Singleton getInstance(String param) {
if (instance == null)
instance = new Singleton(param);
return instance;
}
}
When start application, console will contains next strings:
first
first
first
\|/ 73

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Categories

Resources