The singleton pattern
is one of the simplest design patterns: it involves only one class which is
responsible to instantiate itself, to make sure it creates not more than one
instance; in the same time it provides a global point of access to that
instance. In this case the same instance can be used from everywhere, being
impossible to invoke directly the constructor each time.
Generally, singleton classes use a static variable to
hold a reference their own instance, but as Axapta does not support static
variables we are left with no other option to use the global caching
mechanism to accomplish the similar functionality. Due to the nature of
Axapta global caching, we need to add the instance reference to both the
client- and server-side caches separately.
We should override
the new () method of our singleton
class and use the private access modifier to ensure that it cannot be
instantiated directly. For accessing the instance we will create static method which will act as static accessor method used typically
in normal Singleton pattern implementation.
Implementation
//Accessor method
public static
SingletonClass instance()
{
SingletonClass singleton;
SysGlobalCache globalCache =
infolog.objectOnServer() ? appl.globalCache() : infolog.globalCache();
;
if (globalCache.isSet(classStr(SingletonClass), 0))
singleton = globalCache.get(classStr(SingletonClass),
0);
else
{
singleton = new
SingletonClass();
infoLog.globalCache().set(classStr(SingletonClass),
0, singleton);
appl.globalCache().set(classStr(SingletonClass),
0, singleton);
}
return singleton;
}
//Avoid instantiation publically
private void
new()
{
}
No comments:
Post a Comment