Write a class in such a way that it guarantees that only one object can be created.
Exercise – Restricting a class instantiation to a single shared instance
Answer
Here is one possible solution:
public class SingletonClassExample {
private static SingletonClassExample OBJECT = null;
private SingletonClassExample(){}
public final SingletonClassExample getInstance() {
if(OBJECT == null){
OBJECT = new SingletonClassExample();
}
return OBJECT;
}
//... other class functionality
}
Another solution could be to make the class private inside the factory class and store it in the factory field, similarly to the previous code.
Be aware, though, that if such a single object has a state that is changing, one has...