"C<_instance>", is coerced into the derived class package rather than the base
class package.
Thus, in the C<MyApp::Database> example above, the instance variable would
be:
$MyApp::Database::_instance;
This allows different classes to be derived from C<Class::Singleton> that can
co-exist in the same system, while still allowing only one instance of any one
class to exists. For example, it would be possible to derive both
'C<PrintSpooler>' and 'C<MyApp::Database>' from C<Class::Singleton> and have a
single instance of I<each> in a system, rather than a single instance of
I<either>.
You can use the L<has_instance()> method to find out if a particular class
already has an instance defined. A reference to the instance is returned or
C<undef> if none is currently defined.
my $instance = MyApp::Database->has_instance()
|| warn "No instance is defined yet";
=head1 METHODS
=head2 instance()
This method is called to return a current object instance or create a new
one by calling L<_new_instance()>.
=head2 has_instance()
This method returns a reference to any existing instance or C<undef> if none
is defined.
my $testing = MySingleton1->has_instance()
|| warn "No instance defined for MySingleton1";
=head2 _new_instance()
This "private" method is called by L<instance()> to create a new object
instance if one doesn't already exist. It is not intended to be called
directly (although there's nothing to stop you from calling it if you're
really determined to do so).
It creates a blessed hash reference containing any arguments passed to the
method as either a hash reference or list of named parameters.
# either: hash reference of named parameters
my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });
# or: list of named parameters
my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );
It is important to remember that the L<instance()> method will I<only> call
the I<_new_instance()> method once, so any arguments you pass may be silently
ignored if an instance already exists. You can use the L<has_instance()>
method to determine if an instance is already defined.
=head1 AUTHOR
Andy Wardley E<lt>abw@wardley.orgE<gt> L<http://wardley.org/>
Thanks to Andreas Koenig for providing some significant speedup patches and
other ideas.
=head1 VERSION
This is version 1.4, released September 2007
=head1 COPYRIGHT
Copyright Andy Wardley 1998-2007. All Rights Reserved.
This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.
=cut
=4=
THE END |