Prepared singleton pattern

From Wikipedia, the free encyclopedia

In software engineering, the prepared singleton is design pattern that is one of the many extensions to the basic singleton idea, where a class is only permitted one instance. The method by which the second and subsequent instances are prohibited is governed by the language.

One of the main implementation problems with singletons is that they can be created at any time, by any unwitting class. Prepared singletons avoid this problem by creating the single instance of every class at the start of the program. This is often achieved by supplementing the Get function with a Create function. Although this creates more objects than perhaps is necessary, you can easily force the code into a “worse case scenario,” which may be helpful when implementing on an embedded system.

This creates a much bigger win scenario when one class is derived from another, especially when the base class is a null driver. Consider the graphics API example in the double-chance function section, where CNewGfxAPI is a singleton derived from CBaseGfxAPI. Here we can prepare the CNewGfxAPI class as soon as possible, while using CBaseGfxAPI throughout the code. Since they share the ms_pSelf pointer there will still only be one instance of the either class, but the virtual functions will correctly bind each call to the correct function in the derived class. In this way the code using the API doesn’t need to change, and the entire behaviour of the code can change by preparing a different singleton at the beginning of the program.

Remember that because Get never creates the singleton, the function itself can be inlined to a speedy:

inline CBaseGfxAPI *Get() { return m_pSelf; }

While the Create function of every class (and its derivations) adopts a nice:

CBaseGfxAPI * CNewGfxAPI::Create()
{
    if (ms_pSelf == NULL) {
        ms_pSelf = new CNewGfxAPI;
    }
    return ms_pSelf;            
}

[edit] Reference

  • Goodwin, Steven (2005). Cross-Platform Game Programming. Charles River Media. ISBN 1-58450-379-3.