We've created a simple 2D game, it has fields and elements on it, the player can move the elements. The game has two views: a graphical (with images), and a textual (printed to the console). But only one at the time, and the game's logic must not know about the actual view.

To solve this, I created a factory interface. At startup time, a class that implements this interface (GUI or CMD factory) is created and stored in the main class. Now I can create views, but the models don't have to know about those. Perfect.

However, I noticed that I have to call MysteryWindow.blah().blah().getActualViewFactory() each time, but if we look the factory as a black box (and the game's models must do), it's not really an instance/property but a kind of singleton. So I could do a refactoring:

public class ViewFactory {
    private static ViewFactoryImpl instance;
    public void setup() { if (someConfig) instance = new GUIViewFactory(); }
    public static View createXXField(XX field) { instance.createXXField(field); }
    public static View createXXElement(XX element) {  instance.createXXElement(field); }

The example is pretty trivial and not worth restructuring the whole project now, but I'd like to know that is this kind of design good? If no, why? Could we call this new class a singleton if it's operation can vary (bettween two runs)?

1 Answer 1


The essential thing about a Singleton is that there is one call which will return the same instance each time, which makes sure that the instance is available on the first call, and which makes sure that the instance stays available throughout execution of the program. As long as you provide this, you are fine.

There is no requirement that the Singleton would belong to the same class on every run, or behaves the same on every run, as long as it behaves according to its interface.

It would be preferable if there is no public "setup" function, since you should be able to use the Singleton at any time, not limited to a time after some initialisation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.