[ fromfile: singleton.xml id: singleton ]
As discussed earlier, the Singleton pattern is a specialized factory used in situations where we wish to limit the number or type of instances created.
The CustomerFactory::instance()
method, defined in Example 16.7, is an example of a singleton factory.
It creates an object if needed, but only the first time that the method is called.
On subsequent calls it always returns a pointer to the same object.
Example 16.7. src/libs/customer/customerfactory.cpp
[ . . . . ] CustomerFactory* CustomerFactory::instance() { static CustomerFactory* retval = 0; if (retval == 0) retval = new CustomerFactory(qApp); return retval; }
<include src="src/libs/customer/customerfactory.cpp" mode="cpp" href="src/libs/customer/customerfactory.cpp" id="objfac-instance" segid="singleton"/>
It is important when dealing with heap objects that you do not leave memory leaks behind. You can use QObject's parent-child relationship to help in this regard.
As mentioned earlier, qApp
is a pointer to a singleton instance of QApplication, which was presumably created in main()
.
The QApplication instance exists precisely as long as the application is running.
Why Not Use a static Parent? | |
---|---|
If you make the parent of your heap objects a |
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |