Formeln

Saturday, May 12, 2012

Organizing your Code: Singletons

If you have an object, that has to be referenced by many other objects thoughout your code it becomes annoying to pass this object every time as a reference. One solution to this problem is using the Singleton Design Pattern. You can read more about the Singleton Pattern here:
http://en.wikipedia.org/wiki/Singleton_pattern

Basically you use this pattern, if you have just one object of this Class in your whole program.
The DeviceManager is a good candidate for a Singleton, because you create the device just once and use it until your program ends. All Classes, that use the Singleton Pattern will be called Managers in my code.


public class DeviceManager
{
    private static DeviceManager instance = null;
    public static DeviceManager Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new DeviceManager();
            }
            return instance;
        }
    }

    private DeviceManager(){}

    
    Device device;

}

The device in the DeviceManager can then be accessed over your whole code with:

DeviceManager.Instance.device

Now also change the RenderManager to the Singleton Pattern and then our Form1 looks like this:

public Form1()
{
    InitializeComponent();
    DeviceManager.Instance.createDeviceAndSwapChain(this);
    RenderManager.Instance.init();
}

public void shutDown()
{
    RenderManager.Instance.shutDown();
    DeviceManager.Instance.shutDown();
}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    shutDown();
}

No comments:

Post a Comment