VR-Vantage 3.0 API Documentation
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
10.2 - The Rooted Singleton Pattern

Table of Contents

The Singleton pattern provides a single global instance of a class to an application.

The Rooted Singleton pattern provides a single global instance of a class associated with a specific root object. It allows Toolkit users to create applications that have two display engines without having them interfere with each other.

The Rooted Singleton pattern involves two classes, the singleton class and the root object class. The singleton class is globally accessed. The root object class is the scope in which the singleton class lives.

Suppose that you want to have two display engine instances in your application. You want to override one of them so that it creates your own derived channel whenever a channel is created, but you want the other display engine to behave normally. If we used the standard Singleton pattern you could not do that. If you overrode the channel creator with your own channel creator, then both display engines would create your derived channel, which is not what you want. The Rooted Singleton pattern lets you register a new channel creator with one instance of the display engine, but leaves the other instance alone.

To create a Rooted Singleton, do something like this:

// Example Rooted Singleton
class MyExampleSingleton : public DtVirtualBaseClass
{
public:
// Lazily create a global instance rooted off a Display Engine
static MyExampleSingleton& instance(DtDE displayEngine)
{
MyExampleSingleton* singleton = dynamic_cast<MyExampleSingleton*>(
displayEngine.findInstance("MyExampleSingleton"));
if(!singleton)
{
singleton = new MyExampleSingleton();
displayEngine.registerInstance(
"MyExampleSingleton",singleton);
}
return *singleton;
}
// DTOR
virtual ~MyExampleSingleton();
// Your methods here...
void myExampleMethod()
{
}
private:
// Private CTOR.
MyExampleSingleton();
};

The singleton lazily creates and registers itself with the display engine. Under the hood, the display engine simply has a map of DtVirtualBaseClasses with std::string keys. When you access this object you use the static instance() method:

MyExampleSingleton::instance(displayEngine).myExampleMethod();

The first time this object is accessed, it is created and registered with the display engine using the key MyExampleSingleton. The next time it is accessed, the singleton is just returned. The singleton lives throughout the existence of the display engine. When the display engine is destroyed, all the Rooted Singletons are deleted.

10.2.1 The Rooted Singleton Pattern Specification

The Rooted Singleton pattern has the following requirements and behavior:

[<< Design Patterns] [Home] [Top of Page] [The Signaler Pattern >>]



Copyright © 2005-2022 MAK Technologies. All Rights Reserved (www.mak.com)