registerSingleton()
registerSingleton(instance : Object) : Object
If a singleton class constructor requires parameters, before retrieving the singleton instance with instance()
, you must first register it using this method. The singleton shared copy of instance is returned.
Shared object considerations
Because 4D does not allow you to directly instantiate a shared object, this method has to make a shared copy of instance using OB Copy
in order to store it in Storage
. Depending on the structure of instance, OB Copy
may not create a usable copy.
In such cases, you should define an .initShared()
function in instance’s class which takes no parameters and returns nothing. When .initShared()
is called, This
is a shared copy of instance. The function is responsible for completely initializing the shared copy, wrapping any modifications to This
in Use()/End use
.
Example
// Greeter
Class constructor($greeting: Text)
This.greeting:=$greeting#"" ? $greeting : "Hello"
Function greet($name: Text) : Text
return _.format("${1} ${2}!"; This.greeting; $name)
// On Startup
registerSingleton(cs.Greeter.new("Howdy"))
// greetUser
ALERT(instance(cs.Greeter).greet("Laurent"))
// => Howdy Laurent!