<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">#============================================================================
#
# Class::Singleton.pm
#
# Implementation of a "singleton" module which ensures that a class has
# only one instance and provides global access to it.  For a description 
# of the Singleton class, see "Design Patterns", Gamma et al, Addison-
# Wesley, 1995, ISBN 0-201-63361-2
#
# Written by Andy Wardley &lt;abw@wardley.org&gt;
#
# Copyright (C) 1998-2008 Andy Wardley.  All Rights Reserved.
# Copyright (C) 1998 Canon Research Centre Europe Ltd.
#
#============================================================================

package Class::Singleton;
require 5.004;
use strict;
use warnings;

our $VERSION = 1.4;


#========================================================================
#
# instance()
#
# Module constructor.  Creates an Class::Singleton (or derived) instance 
# if one doesn't already exist.  The instance reference is stored in the
# _instance variable of the $class package.  This means that classes 
# derived from Class::Singleton will have the variables defined in *THEIR*
# package, rather than the Class::Singleton package.  The impact of this is
# that you can create any number of classes derived from Class::Singleton
# and create a single instance of each one.  If the _instance variable
# was stored in the Class::Singleton package, you could only instantiate 
# *ONE* object of *ANY* class derived from Class::Singleton.  The first
# time the instance is created, the _new_instance() constructor is called 
# which simply returns a reference to a blessed hash.  This can be 
# overloaded for custom constructors.  Any addtional parameters passed to 
# instance() are forwarded to _new_instance().
#
# Returns a reference to the existing, or a newly created Class::Singleton
# object.  If the _new_instance() method returns an undefined value
# then the constructer is deemed to have failed.
#
#========================================================================

sub instance {
    my $class = shift;
    
    # already got an object
    return $class if ref $class;

    # we store the instance in the _instance variable in the $class package.
    no strict 'refs';
    my $instance = \${ "$class\::_instance" };
    defined $$instance
        ? $$instance
        : ($$instance = $class-&gt;_new_instance(@_));
}


#=======================================================================
# has_instance()
#
# Public method to return the current instance if it exists.
#=======================================================================

sub has_instance {
    my $class = shift;
    $class = ref $class || $class;
    no strict 'refs';
    return ${"$class\::_instance"};
}


#========================================================================
# _new_instance(...)
#
# Simple constructor which returns a hash reference blessed into the 
# current class.  May be overloaded to create non-hash objects or 
# handle any specific initialisation required.
#========================================================================

sub _new_instance {
    my $class = shift;
    my %args  = @_ &amp;&amp; ref $_[0] eq 'HASH' ? %{ $_[0] } : @_;
    bless { %args }, $class;
}



1;

__END__

=head1 NAME

Class::Singleton - Implementation of a "Singleton" class 

=head1 SYNOPSIS

    use Class::Singleton;
    
    my $one = Class::Singleton-&gt;instance();   # returns a new instance
    my $two = Class::Singleton-&gt;instance();   # returns same instance

=head1 DESCRIPTION

This is the C&lt;Class::Singleton&gt; module.  A Singleton describes an object class
that can have only one instance in any system.  An example of a Singleton
might be a print spooler or system registry.  This module implements a
Singleton class from which other classes can be derived.  By itself, the
C&lt;Class::Singleton&gt; module does very little other than manage the instantiation
of a single object.  In deriving a class from C&lt;Class::Singleton&gt;, your module 
will inherit the Singleton instantiation method and can implement whatever
specific functionality is required.

For a description and discussion of the Singleton class, see 
"Design Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2.

=head1 PREREQUISITES

C&lt;Class::Singleton&gt; requires Perl version 5.004 or later. If you have an older
version of Perl, please upgrade to latest version, available from your nearest
CPAN site (see L&lt;INSTALLATION&gt; below).

=head1 INSTALLATION

The C&lt;Class::Singleton&gt; module is available from CPAN. As the 'perlmod' man
page explains:

    CPAN stands for the Comprehensive Perl Archive Network.
    This is a globally replicated collection of all known Perl
    materials, including hundreds of unbunded modules.
    
    [...]
    
    For an up-to-date listing of CPAN sites, see
    http://www.perl.com/perl/ or ftp://ftp.perl.com/perl/ .

The module is available in the following directories:

    /modules/by-module/Class/Class-Singleton-&lt;version&gt;.tar.gz
    /authors/id/ABW/Class-Singleton-&lt;version&gt;.tar.gz

C&lt;Class::Singleton&gt; is distributed as a single gzipped tar archive file:

    Class-Singleton-&lt;version&gt;.tar.gz

Note that "&lt;version&gt;" represents the current version number, of the 
form "C&lt;1.23&gt;".  See L&lt;VERSION&gt; below to determine the current version 
number for C&lt;Class::Singleton&gt;.

Unpack the archive to create an installation directory:

    gunzip Class-Singleton-&lt;version&gt;.tar.gz
    tar xvf Class-Singleton-&lt;version&gt;.tar

'cd' into that directory, make, test and install the module:

    cd Class-Singleton-&lt;version&gt;
    perl Makefile.PL
    make
    make test
    make install

The 'C&lt;make install&gt;' will install the module on your system.  You may need 
root access to perform this task.  If you install the module in a local 
directory (for example, by executing "C&lt;perl Makefile.PL LIB=~/lib&gt;" in the 
above - see C&lt;perldoc MakeMaker&gt; for full details), you will need to ensure 
that the C&lt;PERL5LIB&gt; environment variable is set to include the location, or 
add a line to your scripts explicitly naming the library location:

    use lib '/local/path/to/lib';

=head1 USING THE CLASS::SINGLETON MODULE

To import and use the C&lt;Class::Singleton&gt; module the following line should 
appear in your Perl program:

    use Class::Singleton;

The L&lt;instance()&gt; method is used to create a new C&lt;Class::Singleton&gt; instance,
or return a reference to an existing instance. Using this method, it is only
possible to have a single instance of the class in any system.

    my $highlander = Class::Singleton-&gt;instance();

Assuming that no C&lt;Class::Singleton&gt; object currently exists, this first call
to L&lt;instance()&gt; will create a new C&lt;Class::Singleton&gt; and return a reference
to it. Future invocations of L&lt;instance()&gt; will return the same reference.

    my $macleod    = Class::Singleton-&gt;instance();

In the above example, both C&lt;$highlander&gt; and C&lt;$macleod&gt; contain the same
reference to a C&lt;Class::Singleton&gt; instance.  There can be only one.

=head1 DERIVING SINGLETON CLASSES

A module class may be derived from C&lt;Class::Singleton&gt; and will inherit the 
L&lt;instance()&gt; method that correctly instantiates only one object.

    package PrintSpooler;
    use base 'Class::Singleton';
    
    # derived class specific code
    sub submit_job {
        ...
    }
    
    sub cancel_job {
        ...
    }

The C&lt;PrintSpooler&gt; class defined above could be used as follows:

    use PrintSpooler;
    
    my $spooler = PrintSpooler-&gt;instance();
    
    $spooler-&gt;submit_job(...);

The L&lt;instance()&gt; method calls the L&lt;_new_instance()&gt; constructor method the
first and only time a new instance is created. All parameters passed to the
L&lt;instance()&gt; method are forwarded to L&lt;_new_instance()&gt;. In the base class
the L&lt;_new_instance()&gt; method returns a blessed reference to a hash array
containing any arguments passed as either a hash reference or list of named 
parameters. 

    package MyConfig;
    use base 'Class::Singleton';
    
    sub foo {
        shift-&gt;{ foo };
    }
    
    sub bar {
        shift-&gt;{ bar };
    }
    
    package main;
    
    # either: hash reference of named parameters
    my $config = MyConfig-&gt;instance({ foo =&gt; 10, bar =&gt; 20 });
    
    # or: list of named parameters
    my $config = MyConfig-&gt;instance( foo =&gt; 10, bar =&gt; 20 );
    
    print $config-&gt;foo();   # 10
    print $config-&gt;bar();   # 20

Derived classes may redefine the L&lt;_new_instance()&gt; method to provide more
specific object initialisation or change the underlying object type (to a list
reference, for example).

    package MyApp::Database;
    use base 'Class::Singleton';
    use DBI;
    
    # this only gets called the first time instance() is called
    sub _new_instance {
        my $class = shift;
        my $self  = bless { }, $class;
        my $db    = shift || "myappdb";    
        my $host  = shift || "localhost";
        
        $self-&gt;{ DB } = DBI-&gt;connect("DBI:mSQL:$db:$host")
            || die "Cannot connect to database: $DBI::errstr";
        
        # any other initialisation...
        
        return $self;
    }

The above example might be used as follows:

    use MyApp::Database;
    
    # first use - database gets initialised
    my $database = MyApp::Database-&gt;instance();

Some time later on in a module far, far away...

    package MyApp::FooBar
    use MyApp::Database;
    
    # this FooBar object needs access to the database; the Singleton
    # approach gives a nice wrapper around global variables.
    
    sub new {
        my $class = shift;
        bless {
            database =&gt; MyApp::Database-&gt;instance(),
        }, $class;
    }

The C&lt;Class::Singleton&gt; L&lt;instance()&gt; method uses a package variable to store
a reference to any existing instance of the object. This variable,
"C&lt;_instance&gt;", is coerced into the derived class package rather than the base
class package.

Thus, in the C&lt;MyApp::Database&gt; example above, the instance variable would
be:

    $MyApp::Database::_instance;

This allows different classes to be derived from C&lt;Class::Singleton&gt; 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&lt;PrintSpooler&gt;' and 'C&lt;MyApp::Database&gt;' from C&lt;Class::Singleton&gt; and have a
single instance of I&lt;each&gt; in a system, rather than a single instance of
I&lt;either&gt;.

You can use the L&lt;has_instance()&gt; method to find out if a particular class 
already has an instance defined.  A reference to the instance is returned or
C&lt;undef&gt; if none is currently defined.

    my $instance = MyApp::Database-&gt;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&lt;_new_instance()&gt;.

=head2 has_instance()

This method returns a reference to any existing instance or C&lt;undef&gt; if none
is defined.

    my $testing = MySingleton1-&gt;has_instance()
        || warn "No instance defined for MySingleton1";

=head2 _new_instance()

This "private" method is called by L&lt;instance()&gt; 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-&gt;new({ pi =&gt; 3.14, e =&gt; 2.718 });

    # or: list of named parameters
    my $example2 = MySingleton2-&gt;new( pi =&gt; 3.14, e =&gt; 2.718 );

It is important to remember that the L&lt;instance()&gt; method will I&lt;only&gt; call
the I&lt;_new_instance()&gt; method once, so any arguments you pass may be silently
ignored if an instance already exists. You can use the L&lt;has_instance()&gt;
method to determine if an instance is already defined.

=head1 AUTHOR

Andy Wardley E&lt;lt&gt;abw@wardley.orgE&lt;gt&gt; L&lt;http://wardley.org/&gt;

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
</pre></body></html>