1Class::Singleton(3)   User Contributed Perl Documentation  Class::Singleton(3)
2
3
4

NAME

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

SYNOPSIS

9           use Class::Singleton;
10
11           my $one = Class::Singleton->instance();   # returns a new instance
12           my $two = Class::Singleton->instance();   # returns same instance
13

DESCRIPTION

15       This is the "Class::Singleton" module.  A Singleton describes an object
16       class that can have only one instance in any system.  An example of a
17       Singleton might be a print spooler or system registry.  This module
18       implements a Singleton class from which other classes can be derived.
19       By itself, the "Class::Singleton" module does very little other than
20       manage the instantiation of a single object.  In deriving a class from
21       "Class::Singleton", your module will inherit the Singleton
22       instantiation method and can implement whatever specific functionality
23       is required.
24
25       For a description and discussion of the Singleton class, see "Design
26       Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2.
27

PREREQUISITES

29       "Class::Singleton" requires Perl version 5.004 or later. If you have an
30       older version of Perl, please upgrade to latest version, available from
31       your nearest CPAN site (see INSTALLATION below).
32

INSTALLATION

34       The "Class::Singleton" module is available from CPAN. As the 'perlmod'
35       man page explains:
36
37           CPAN stands for the Comprehensive Perl Archive Network.
38           This is a globally replicated collection of all known Perl
39           materials, including hundreds of unbunded modules.
40
41           [...]
42
43           For an up-to-date listing of CPAN sites, see
44           http://www.perl.com/perl/ or ftp://ftp.perl.com/perl/ .
45
46       The module is available in the following directories:
47
48           /modules/by-module/Class/Class-Singleton-<version>.tar.gz
49           /authors/id/ABW/Class-Singleton-<version>.tar.gz
50
51       "Class::Singleton" is distributed as a single gzipped tar archive file:
52
53           Class-Singleton-<version>.tar.gz
54
55       Note that "<version>" represents the current version number, of the
56       form "1.23".  See VERSION below to determine the current version number
57       for "Class::Singleton".
58
59       Unpack the archive to create an installation directory:
60
61           gunzip Class-Singleton-<version>.tar.gz
62           tar xvf Class-Singleton-<version>.tar
63
64       'cd' into that directory, make, test and install the module:
65
66           cd Class-Singleton-<version>
67           perl Makefile.PL
68           make
69           make test
70           make install
71
72       The '"make install"' will install the module on your system.  You may
73       need root access to perform this task.  If you install the module in a
74       local directory (for example, by executing ""perl Makefile.PL
75       LIB=~/lib"" in the above - see "perldoc MakeMaker" for full details),
76       you will need to ensure that the "PERL5LIB" environment variable is set
77       to include the location, or add a line to your scripts explicitly
78       naming the library location:
79
80           use lib '/local/path/to/lib';
81

USING THE CLASS::SINGLETON MODULE

83       To import and use the "Class::Singleton" module the following line
84       should appear in your Perl program:
85
86           use Class::Singleton;
87
88       The instance() method is used to create a new "Class::Singleton"
89       instance, or return a reference to an existing instance. Using this
90       method, it is only possible to have a single instance of the class in
91       any system.
92
93           my $highlander = Class::Singleton->instance();
94
95       Assuming that no "Class::Singleton" object currently exists, this first
96       call to instance() will create a new "Class::Singleton" and return a
97       reference to it. Future invocations of instance() will return the same
98       reference.
99
100           my $macleod    = Class::Singleton->instance();
101
102       In the above example, both $highlander and $macleod contain the same
103       reference to a "Class::Singleton" instance.  There can be only one.
104

DERIVING SINGLETON CLASSES

106       A module class may be derived from "Class::Singleton" and will inherit
107       the instance() method that correctly instantiates only one object.
108
109           package PrintSpooler;
110           use base 'Class::Singleton';
111
112           # derived class specific code
113           sub submit_job {
114               ...
115           }
116
117           sub cancel_job {
118               ...
119           }
120
121       The "PrintSpooler" class defined above could be used as follows:
122
123           use PrintSpooler;
124
125           my $spooler = PrintSpooler->instance();
126
127           $spooler->submit_job(...);
128
129       The instance() method calls the _new_instance() constructor method the
130       first and only time a new instance is created. All parameters passed to
131       the instance() method are forwarded to _new_instance(). In the base
132       class the _new_instance() method returns a blessed reference to a hash
133       array containing any arguments passed as either a hash reference or
134       list of named parameters.
135
136           package MyConfig;
137           use base 'Class::Singleton';
138
139           sub foo {
140               shift->{ foo };
141           }
142
143           sub bar {
144               shift->{ bar };
145           }
146
147           package main;
148
149           # either: hash reference of named parameters
150           my $config = MyConfig->instance({ foo => 10, bar => 20 });
151
152           # or: list of named parameters
153           my $config = MyConfig->instance( foo => 10, bar => 20 );
154
155           print $config->foo();   # 10
156           print $config->bar();   # 20
157
158       Derived classes may redefine the _new_instance() method to provide more
159       specific object initialisation or change the underlying object type (to
160       a list reference, for example).
161
162           package MyApp::Database;
163           use base 'Class::Singleton';
164           use DBI;
165
166           # this only gets called the first time instance() is called
167           sub _new_instance {
168               my $class = shift;
169               my $self  = bless { }, $class;
170               my $db    = shift || "myappdb";
171               my $host  = shift || "localhost";
172
173               $self->{ DB } = DBI->connect("DBI:mSQL:$db:$host")
174                   || die "Cannot connect to database: $DBI::errstr";
175
176               # any other initialisation...
177
178               return $self;
179           }
180
181       The above example might be used as follows:
182
183           use MyApp::Database;
184
185           # first use - database gets initialised
186           my $database = MyApp::Database->instance();
187
188       Some time later on in a module far, far away...
189
190           package MyApp::FooBar
191           use MyApp::Database;
192
193           # this FooBar object needs access to the database; the Singleton
194           # approach gives a nice wrapper around global variables.
195
196           sub new {
197               my $class = shift;
198               bless {
199                   database => MyApp::Database->instance(),
200               }, $class;
201           }
202
203       The "Class::Singleton" instance() method uses a package variable to
204       store a reference to any existing instance of the object. This
205       variable, ""_instance"", is coerced into the derived class package
206       rather than the base class package.
207
208       Thus, in the "MyApp::Database" example above, the instance variable
209       would be:
210
211           $MyApp::Database::_instance;
212
213       This allows different classes to be derived from "Class::Singleton"
214       that can co-exist in the same system, while still allowing only one
215       instance of any one class to exists. For example, it would be possible
216       to derive both '"PrintSpooler"' and '"MyApp::Database"' from
217       "Class::Singleton" and have a single instance of each in a system,
218       rather than a single instance of either.
219
220       You can use the has_instance() method to find out if a particular class
221       already has an instance defined.  A reference to the instance is
222       returned or "undef" if none is currently defined.
223
224           my $instance = MyApp::Database->has_instance()
225               || warn "No instance is defined yet";
226

METHODS

228   instance()
229       This method is called to return a current object instance or create a
230       new one by calling _new_instance().
231
232   has_instance()
233       This method returns a reference to any existing instance or "undef" if
234       none is defined.
235
236           my $testing = MySingleton1->has_instance()
237               || warn "No instance defined for MySingleton1";
238
239   _new_instance()
240       This "private" method is called by instance() to create a new object
241       instance if one doesn't already exist. It is not intended to be called
242       directly (although there's nothing to stop you from calling it if
243       you're really determined to do so).
244
245       It creates a blessed hash reference containing any arguments passed to
246       the method as either a hash reference or list of named parameters.
247
248           # either: hash reference of named parameters
249           my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });
250
251           # or: list of named parameters
252           my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );
253
254       It is important to remember that the instance() method will only call
255       the _new_instance() method once, so any arguments you pass may be
256       silently ignored if an instance already exists. You can use the
257       has_instance() method to determine if an instance is already defined.
258

AUTHOR

260       Andy Wardley <abw@wardley.org> <http://wardley.org/>
261
262       Thanks to Andreas Koenig for providing some significant speedup patches
263       and other ideas.
264

VERSION

266       This is version 1.4, released September 2007
267
269       Copyright Andy Wardley 1998-2007.  All Rights Reserved.
270
271       This module is free software; you can redistribute it and/or modify it
272       under the same terms as Perl itself.
273
274
275
276perl v5.12.0                      2007-09-28               Class::Singleton(3)
Impressum