You can use oclSingleton in an OCL expression to retrieve the single instance of a modeled singleton class, creating that instance when it does not already exist.
What oclSingleton does
oclSingleton implements the Singleton pattern in OCL. A singleton class is a class intended to have one object instance: no more and no less.
When you evaluate ClassName.oclSingleton:
- MDriven returns the single instance of
ClassName. - If no instance exists at evaluation time, MDriven creates one.
- You can then navigate associations, read attributes, or continue the expression from that object.
This is useful when model logic needs shared application state in the model context. For example, a singleton can hold a CurrentUser association that makes the logged-in user available to expressions.
Configure a singleton class
To use oclSingleton, mark the class as a singleton in the model.
- Select the class in MDriven Designer.
- Set the class tagged value
Eco.IsSingletontotrue. - Use
ClassName.oclSingletonin an OCL expression where you need the singleton object.
For example, configure the class SysSingleton with Eco.IsSingleton=true. You can then retrieve its object with:
SysSingleton.oclSingleton
Syntax
ClassName.oclSingleton
ClassName is the class marked with Eco.IsSingleton=true. The result is the singleton object, so continue with a property or association navigation as needed.
Example: access the current user
Assume that SysSingleton has an association named CurrentUser, and that the user class has the Boolean attribute IsAdmin.
SysSingleton.oclSingleton.CurrentUser.IsAdmin
This expression obtains the SysSingleton object, follows its CurrentUser association, and evaluates IsAdmin for that user.
When to use it
Use oclSingleton when your model needs one shared object with model-visible state or behavior. Because the singleton can have code-derived attributes and associations, it can expose information from the running environment through the model.
For example, instead of introducing separate global variables for application-wide state, model a SysSingleton class and place the relevant associations or code-derived attributes on it. Expressions can then access that state through SysSingleton.oclSingleton.
Alternative access
A singleton object can also be reached by retrieving all instances and selecting the first one:
SysSingleton.allinstances->first
Use oclSingleton for a class designed as a singleton. Unlike the alternative expression, it explicitly represents the singleton intent and creates the instance if one does not exist.
