Singleton pattern

A singleton is a class which only allows a single instance of itself to be created. An instance of a singleton class is not created until the first time it is requested.

Usually, singleton classes use a static variable to hold a reference their own instance, but as Axapta does not support static variables we are forced to use the global caching mechanism to achieve the same effect. Due to the nature of Axapta global caching, we need to add the instance reference to both the client- and server-side caches separately.

For safety, it should be impossible for an instance of a singleton class to be created directly (without using the accessor static method). We should therefore override the new method of our singleton class and use the private access modifier to ensure that it cannot be instantiated directly.

The following static method can be modified and added to a class to make it a singleton.

// RunOn:CalledFrom public static SingletonTest instance {   SingletonTest   singleton; SysGlobalCache globalCache = infolog.objectOnServer ? appl.globalCache : infolog.globalCache; ;   if (globalCache.isSet(classStr(SingletonTest), 0)) singleton = globalCache.get(classStr(SingletonTest), 0); else {       singleton = new SingletonTest; infoLog.globalCache.set(classStr(SingletonTest), 0, singleton); appl.globalCache.set(classStr(SingletonTest), 0, singleton); }   return singleton; }

We should also make the following change, adding the private keyword to the constructor to stop it being instantiated from outside the instance method

private void new { }