Exercise – Restricting a class instantiation to a single shared instance
Write a class in such a way that it guarantees that only one object can be created.
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 to make sure it is acceptable to modify the state and rely on it concurrently, because this object may be used by different methods at the same time.