I've got an example of where I use a singleton. It's a Dancer2 web application with a JS/jQuery front end. It has a separate module for the API, and one for DB.
All users who view the page see the exact same results. When the page is updated on one device, it's auto-updated on all others as well.
Both the API module (class) and DB module (class) are singletons (as is the log object). This ensures that each user loading the page are using the exact same object, so all configuration of the objects are consistent on all runs. If the DB or API objects modify themselves throughout the course of their duties, all instances of the application immediately have those attributes/changes provided.
Here's some of the code from the API module:
# the $api object is declared up here in file scope
sub new {
# return the stored object if we've already run new()
if (defined $api){
$log->_5('returning stored API object');
return $api;
}
my $self = bless {}, shift;
my $caller = (caller)[0];
$self->_args(@_, caller => $caller);
warn "API in test mode\n" if $self->testing;
$self->_init;
$api = $self;
$log->_5("successfully initialized the system");
if (! $self->testing && ! defined $events){
$self->events;
$log->_5('successfully created new async events')
}
else {
$log->_5("async events have already been spawned");
}
return $self;
}
|