Search code examples
design-patternssingletonfactoryfactory-pattern

Direct Injection, Factory Pattern, Singleton Pattern


My program has a window where to draw and works on a model (a class). Many other classes (objects) at runtime will use these two. For this reason I need to keep a reference to them. Until now, I just kept two pointers as member variables in my main GUI class, but now I would like to use a better strategy. Singleton pattern seemed to be ideal, but many says that it is better not to use. Alternatives seems to be Direct Injection (which I think is not ideal for my case) or other patterns, like the Factory Pattern. But Factory pattern creates stuff and does not keep references to the created stuff, or am I wrong? Are there other patterns that could help me to have some kind of global container that keeps references to objects that many other objects will use?


Solution

  • I'm not sure you need to change how the references are kept. The main GUI class keeps track of what is created as part of the application, which is perfectly reasonable.

    Using Singleton basically means "Create some other object than the main GUI class that keeps track of which objects are created. Now instead of asking the GUI class, and object will ask the Singleton instead. If they already ask the GUI class, it fulfills the same purpose as a Singleton does.

    So, if you code looks like this:

    object.myMethod {
    <...>
      draw(mainGuiClass.textWindow, bla, bla, bla);
    

    ...and textWindow is static, you are probably already using mainGuiClass as a Singleton.

    If what happens instead is that methods are invoked like this object.someMethod(mainGui.textWindow, bla, bla, bla) or your objects are created with a reference to mainGuiClass or mainGuiClass.textWindow, you are using some kind of Injection.

    Does this help?