5
5
use Class::Singleton;
7
7
my $one = Class::Singleton->instance(); # returns a new instance
8
8
my $two = Class::Singleton->instance(); # returns same instance
11
This is the Class::Singleton module. A Singleton describes an
12
object class that can have only one instance in any system. An
13
example of a Singleton might be a print spooler or system
14
registry. This module implements a Singleton class from which
15
other classes can be derived. By itself, the Class::Singleton
16
module does very little other than manage the instantiation of a
17
single object. In deriving a class from Class::Singleton, your
18
module will inherit the Singleton instantiation method and can
19
implement whatever specific functionality is required.
11
This is the "Class::Singleton" module. A Singleton describes an object
12
class that can have only one instance in any system. An example of a
13
Singleton might be a print spooler or system registry. This module
14
implements a Singleton class from which other classes can be derived. By
15
itself, the "Class::Singleton" module does very little other than manage
16
the instantiation of a single object. In deriving a class from
17
"Class::Singleton", your module will inherit the Singleton instantiation
18
method and can implement whatever specific functionality is required.
21
For a description and discussion of the Singleton class, see
22
"Design Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-
20
For a description and discussion of the Singleton class, see "Design
21
Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2.
26
Class::Singleton requires Perl version 5.004 or later. If you
27
have an older version of Perl, please upgrade to latest version.
28
Perl 5.004 is known to be stable and includes new features and
29
bug fixes over previous versions. Perl itself is available from
24
"Class::Singleton" requires Perl version 5.004 or later. If you have an
25
older version of Perl, please upgrade to latest version, available from
30
26
your nearest CPAN site (see INSTALLATION below).
33
The Class::Singleton module is available from CPAN. As the
34
'perlmod' man page explains:
29
The "Class::Singleton" module is available from CPAN. As the 'perlmod'
36
32
CPAN stands for the Comprehensive Perl Archive Network.
37
33
This is a globally replicated collection of all known Perl
38
34
materials, including hundreds of unbunded modules.
42
38
For an up-to-date listing of CPAN sites, see
43
39
http://www.perl.com/perl/ or ftp://ftp.perl.com/perl/ .
78
The 'make install' will install the module on your system. You
79
may need root access to perform this task. If you install the
80
module in a local directory (for example, by executing "perl
81
Makefile.PL LIB=~/lib" in the above - see `perldoc MakeMaker'
82
for full details), you will need to ensure that the PERL5LIB
83
environment variable is set to include the location, or add a
84
line to your scripts explicitly naming the library location:
67
The '"make install"' will install the module on your system. You may
68
need root access to perform this task. If you install the module in a
69
local directory (for example, by executing ""perl Makefile.PL
70
LIB=~/lib"" in the above - see "perldoc MakeMaker" for full details),
71
you will need to ensure that the "PERL5LIB" environment variable is set
72
to include the location, or add a line to your scripts explicitly naming
86
75
use lib '/local/path/to/lib';
88
77
USING THE CLASS::SINGLETON MODULE
89
To import and use the Class::Singleton module the following line
90
should appear in your Perl script:
78
To import and use the "Class::Singleton" module the following line
79
should appear in your Perl program:
92
81
use Class::Singleton;
94
The instance() method is used to create a new Class::Singleton
95
instance, or return a reference to an existing instance. Using
96
this method, it is only possible to have a single instance of
97
the class in any system.
83
The instance() method is used to create a new "Class::Singleton"
84
instance, or return a reference to an existing instance. Using this
85
method, it is only possible to have a single instance of the class in
99
88
my $highlander = Class::Singleton->instance();
101
Assuming that no Class::Singleton object currently exists, this
102
first call to instance() will create a new Class::Singleton and
103
return a reference to it. Future invocations of instance() will
104
return the same reference.
90
Assuming that no "Class::Singleton" object currently exists, this first
91
call to instance() will create a new "Class::Singleton" and return a
92
reference to it. Future invocations of instance() will return the same
106
95
my $macleod = Class::Singleton->instance();
108
In the above example, both $highlander and $macleod contain the
109
same reference to a Class::Singleton instance. There can be only
97
In the above example, both $highlander and $macleod contain the same
98
reference to a "Class::Singleton" instance. There can be only one.
112
100
DERIVING SINGLETON CLASSES
113
A module class may be derived from Class::Singleton and will
114
inherit the instance() method that correctly instantiates only
101
A module class may be derived from "Class::Singleton" and will inherit
102
the instance() method that correctly instantiates only one object.
117
104
package PrintSpooler;
119
@ISA = qw(Class::Singleton);
105
use base 'Class::Singleton';
121
107
# derived class specific code
130
The PrintSpooler class defined above could be used as follows:
116
The "PrintSpooler" class defined above could be used as follows:
132
118
use PrintSpooler;
134
120
my $spooler = PrintSpooler->instance();
136
122
$spooler->submit_job(...);
138
The instance() method calls the _new_instance() constructor
139
method the first and only time a new instance is created. All
140
parameters passed to the instance() method are forwarded to
141
_new_instance(). In the base class this method returns a blessed
142
reference to an empty hash array. Derived classes may redefine
143
it to provide specific object initialisation or change the
144
underlying object type (to a list reference, for example).
124
The instance() method calls the _new_instance() constructor method the
125
first and only time a new instance is created. All parameters passed to
126
the instance() method are forwarded to _new_instance(). In the base
127
class the _new_instance() method returns a blessed reference to a hash
128
array containing any arguments passed as either a hash reference or list
132
use base 'Class::Singleton';
144
# either: hash reference of named parameters
145
my $config = MyConfig->instance({ foo => 10, bar => 20 });
147
# or: list of named parameters
148
my $config = MyConfig->instance( foo => 10, bar => 20 );
150
print $config->foo(); # 10
151
print $config->bar(); # 20
153
Derived classes may redefine the _new_instance() method to provide more
154
specific object initialisation or change the underlying object type (to
155
a list reference, for example).
146
157
package MyApp::Database;
147
use vars qw( $ERROR );
148
use base qw( Class::Singleton );
158
use base 'Class::Singleton';
153
161
# this only gets called the first time instance() is called
154
162
sub _new_instance {
155
163
my $class = shift;
156
164
my $self = bless { }, $class;
157
165
my $db = shift || "myappdb";
158
166
my $host = shift || "localhost";
160
unless (defined ($self->{ DB }
161
= DBI->connect("DBI:mSQL:$db:$host"))) {
162
$ERROR = "Cannot connect to database: $DBI::errstr\n";
168
$self->{ DB } = DBI->connect("DBI:mSQL:$db:$host")
169
|| die "Cannot connect to database: $DBI::errstr";
167
171
# any other initialisation...
173
176
The above example might be used as follows:
175
178
use MyApp::Database;
177
180
# first use - database gets initialised
178
181
my $database = MyApp::Database->instance();
179
die $MyApp::Database::ERROR unless defined $database;
181
183
Some time later on in a module far, far away...
183
185
package MyApp::FooBar
184
186
use MyApp::Database;
188
# this FooBar object needs access to the database; the Singleton
189
# approach gives a nice wrapper around global variables.
189
# this FooBar object needs access to the database; the Singleton
190
# approach gives a nice wrapper around global variables.
192
# subsequent use - existing instance gets returned
193
my $database = MyApp::Database->instance();
195
# the new() isn't called if an instance already exists,
196
# so the above constructor shouldn't fail, but we check
197
# anyway. One day things might change and this could be the
198
# first call to instance()...
199
die $MyAppDatabase::ERROR unless defined $database;
194
database => MyApp::Database->instance(),
204
The Class::Singleton instance() method uses a package variable
205
to store a reference to any existing instance of the object.
206
This variable, "_instance", is coerced into the derived class
207
package rather than the base class package.
198
The "Class::Singleton" instance() method uses a package variable to
199
store a reference to any existing instance of the object. This variable,
200
""_instance"", is coerced into the derived class package rather than the
209
Thus, in the MyApp::Database example above, the instance
203
Thus, in the "MyApp::Database" example above, the instance variable
212
206
$MyApp::Database::_instance;
214
This allows different classes to be derived from
215
Class::Singleton that can co-exist in the same system, while
216
still allowing only one instance of any one class to exists. For
217
example, it would be possible to derive both 'PrintSpooler' and
218
'MyApp::Database' from Class::Singleton and have a single
219
instance of *each* in a system, rather than a single instance of
208
This allows different classes to be derived from "Class::Singleton" that
209
can co-exist in the same system, while still allowing only one instance
210
of any one class to exists. For example, it would be possible to derive
211
both '"PrintSpooler"' and '"MyApp::Database"' from "Class::Singleton"
212
and have a single instance of *each* in a system, rather than a single
213
instance of *either*.
215
You can use the has_instance() method to find out if a particular class
216
already has an instance defined. A reference to the instance is returned
217
or "undef" if none is currently defined.
219
my $instance = MyApp::Database->has_instance()
220
|| warn "No instance is defined yet";
224
This method is called to return a current object instance or create a
225
new one by calling _new_instance().
228
This method returns a reference to any existing instance or "undef" if
231
my $testing = MySingleton1->has_instance()
232
|| warn "No instance defined for MySingleton1";
235
This "private" method is called by instance() to create a new object
236
instance if one doesn't already exist. It is not intended to be called
237
directly (although there's nothing to stop you from calling it if you're
238
really determined to do so).
240
It creates a blessed hash reference containing any arguments passed to
241
the method as either a hash reference or list of named parameters.
243
# either: hash reference of named parameters
244
my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });
246
# or: list of named parameters
247
my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );
249
It is important to remember that the instance() method will *only* call
250
the *_new_instance()* method once, so any arguments you pass may be
251
silently ignored if an instance already exists. You can use the
252
has_instance() method to determine if an instance is already defined.
223
Andy Wardley, `<abw@cre.canon.co.uk>'
225
Web Technology Group, Canon Research Centre Europe Ltd.
227
Thanks to Andreas Koenig `<andreas.koenig@anima.de>' for
228
providing some significant speedup patches and other ideas.
255
Andy Wardley <abw@wardley.org> <http://wardley.org/>
257
Thanks to Andreas Koenig for providing some significant speedup patches
261
This is version 1.4, released September 2007
234
Copyright (C) 1998 Canon Research Centre Europe Ltd. All Rights
237
This module is free software; you can redistribute it and/or
238
modify it under the term of the Perl Artistic License.
241
Canon Research Centre Europe Perl Pages
242
http://www.cre.canon.co.uk/perl/
244
The Author's Home Page
245
http://www.kfs.org/~abw/
248
Class::Singleton is an implementation of the Singleton class
249
described in "Design Patterns", Gamma et al, Addison-Wesley,
250
1995, ISBN 0-201-63361-2
264
Copyright Andy Wardley 1998-2007. All Rights Reserved.
266
This module is free software; you can redistribute it and/or modify it
267
under the same terms as Perl itself.