Global "get" functions through with Singleton, is it a good idea?



  • Hello everybody..

    I'm here again looking for some advices, so thank you before everything.

    I have some collections in my main application class, but I need to retrieve them from other different classes and I would like to know a good way to achieve that. It looks like this:

    @class Window : QMainWindow {
    // This class handles the collections and is responsible of setting up them
    private:
    DualCollection<Unit> units; //Internally implemented as two QHashes with QString as key type. Don't think it really matters.
    DualCollection<GameItem> items;
    // So on.
    };

    class RosterUnit {
    public:
    void RosterUnit(); // This method need to get a read-only Unit and parse some information. It also needs access to some items
    };

    class ObjectAction {
    public:
    void doAction() = 0; // Some subclasses will eventually need access to some information like Units or Items
    };@

    In fact there are probably other two classes that need to retrieve some information.. I was thinking to use the Singleton pattern with the application class and provide functions like getItem(const QString& key), getUnit(...) and so on, but I'm not sure if it's a good choice. I have read some disadvantages that apply to global variables and singletons like they are hard to debug because they can be modified in the whole application, but it does not apply here because I will provide only a public interface for reading.

    What do you think?

    Thank you very much!



  • Did you note that QApplication is already a singleton class?



  • If you have one and only one instance then yes a singleton is fine and is a commonly used pattern.



  • Uhhh.. I'm sorry.. I meant the main class is derived from QMainWindow..

    Probably it changes your point of view a bit..

    Thank you



  • No, now you're just confusing us. What is yALB? How does it relate to your question?



  • That's the problem of writing when you're leaving house.. Again, I'm sorry..
    I updated the main post.. Basically, the class with collections is derived from QMainWindow.

    Thank you very much!



  • Here is a good read: http://code.google.com/p/google-singleton-detector/wiki/WhySingletonsAreControversial

    I personally find Singletons difficult to use, since the fact whether or not something is a singleton depends on the context. For example, a main window may be a singleton in the application, but during testing, the same class may need to be instantiated multiple times.



  • There is also the chance of making the collections static, so that they are not tied to a particular instance but to the whole application running. Of course if this is possible in your scenario.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.