1Class::Singleton(3) User Contributed Perl Documentation Class::Singleton(3)
2
3
4
6 Class::Singleton - Implementation of a "Singleton" class
7
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
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
28 Using the Class::Singleton Module
29 To import and use the "Class::Singleton" module the following line
30 should appear in your Perl program:
31
32 use Class::Singleton;
33
34 The instance() method is used to create a new "Class::Singleton"
35 instance, or return a reference to an existing instance. Using this
36 method, it is only possible to have a single instance of the class in
37 any system.
38
39 my $highlander = Class::Singleton->instance();
40
41 Assuming that no "Class::Singleton" object currently exists, this first
42 call to instance() will create a new "Class::Singleton" and return a
43 reference to it. Future invocations of instance() will return the same
44 reference.
45
46 my $macleod = Class::Singleton->instance();
47
48 In the above example, both $highlander and $macleod contain the same
49 reference to a "Class::Singleton" instance. There can be only one.
50
51 Deriving Singleton Classes
52 A module class may be derived from "Class::Singleton" and will inherit
53 the instance() method that correctly instantiates only one object.
54
55 package PrintSpooler;
56 use base 'Class::Singleton';
57
58 # derived class specific code
59 sub submit_job {
60 ...
61 }
62
63 sub cancel_job {
64 ...
65 }
66
67 The "PrintSpooler" class defined above could be used as follows:
68
69 use PrintSpooler;
70
71 my $spooler = PrintSpooler->instance();
72
73 $spooler->submit_job(...);
74
75 The instance() method calls the _new_instance() constructor method the
76 first and only time a new instance is created. All parameters passed to
77 the instance() method are forwarded to _new_instance(). In the base
78 class the _new_instance() method returns a blessed reference to a hash
79 array containing any arguments passed as either a hash reference or
80 list of named parameters.
81
82 package MyConfig;
83 use base 'Class::Singleton';
84
85 sub foo {
86 shift->{ foo };
87 }
88
89 sub bar {
90 shift->{ bar };
91 }
92
93 package main;
94
95 # either: hash reference of named parameters
96 my $config = MyConfig->instance({ foo => 10, bar => 20 });
97
98 # or: list of named parameters
99 my $config = MyConfig->instance( foo => 10, bar => 20 );
100
101 print $config->foo(); # 10
102 print $config->bar(); # 20
103
104 Derived classes may redefine the _new_instance() method to provide more
105 specific object initialisation or change the underlying object type (to
106 a list reference, for example).
107
108 package MyApp::Database;
109 use base 'Class::Singleton';
110 use DBI;
111
112 # this only gets called the first time instance() is called
113 sub _new_instance {
114 my $class = shift;
115 my $self = bless { }, $class;
116 my $db = shift || "myappdb";
117 my $host = shift || "localhost";
118
119 $self->{ DB } = DBI->connect("DBI:mSQL:$db:$host")
120 || die "Cannot connect to database: $DBI::errstr";
121
122 # any other initialisation...
123
124 return $self;
125 }
126
127 The above example might be used as follows:
128
129 use MyApp::Database;
130
131 # first use - database gets initialised
132 my $database = MyApp::Database->instance();
133
134 Some time later on in a module far, far away...
135
136 package MyApp::FooBar
137 use MyApp::Database;
138
139 # this FooBar object needs access to the database; the Singleton
140 # approach gives a nice wrapper around global variables.
141
142 sub new {
143 my $class = shift;
144 bless {
145 database => MyApp::Database->instance(),
146 }, $class;
147 }
148
149 The "Class::Singleton" instance() method uses a private hash to store a
150 reference to any existing instance of the object, keyed against the
151 derived class package name.
152
153 This allows different classes to be derived from "Class::Singleton"
154 that can co-exist in the same system, while still allowing only one
155 instance of any one class to exist. For example, it would be possible
156 to derive both '"PrintSpooler"' and '"MyApp::Database"' from
157 "Class::Singleton" and have a single instance of each in a system,
158 rather than a single instance of either.
159
160 You can use the has_instance() method to find out if a particular class
161 already has an instance defined. A reference to the instance is
162 returned or "undef" if none is currently defined.
163
164 my $instance = MyApp::Database->has_instance()
165 || warn "No instance is defined yet";
166
167 Methods
168 instance()
169 This method is called to return a current object instance or create
170 a new one by calling _new_instance().
171
172 has_instance()
173 This method returns a reference to any existing instance or "undef"
174 if none is defined.
175
176 my $testing = MySingleton1->has_instance()
177 || warn "No instance defined for MySingleton1";
178
179 _new_instance()
180 This "private" method is called by instance() to create a new
181 object instance if one doesn't already exist. It is not intended to
182 be called directly (although there's nothing to stop you from
183 calling it if you're really determined to do so).
184
185 It creates a blessed hash reference containing any arguments passed
186 to the method as either a hash reference or list of named
187 parameters.
188
189 # either: hash reference of named parameters
190 my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });
191
192 # or: list of named parameters
193 my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );
194
195 It is important to remember that the instance() method will only
196 call the _new_instance() method once, so any arguments you pass may
197 be silently ignored if an instance already exists. You can use the
198 has_instance() method to determine if an instance is already
199 defined.
200
202 None.
203
205 None.
206
208 Patches, bug reports, suggestions or any other feedback is welcome.
209
210 Patches can be sent as GitHub pull requests at
211 <https://github.com/steve-m-hay/Class-Singleton/pulls>.
212
213 Bug reports and suggestions can be made on the CPAN Request Tracker at
214 <https://rt.cpan.org/Public/Bug/Report.html?Queue=Class-Singleton>.
215
216 Currently active requests on the CPAN Request Tracker can be viewed at
217 <https://rt.cpan.org/Public/Dist/Display.html?Status=Active;Queue=Class-Singleton>.
218
219 Please test this distribution. See CPAN Testers Reports at
220 <https://www.cpantesters.org/> for details of how to get involved.
221
222 Previous test results on CPAN Testers Reports can be viewed at
223 <https://www.cpantesters.org/distro/C/Class-Singleton.html>.
224
225 Please rate this distribution on CPAN Ratings at
226 <https://cpanratings.perl.org/rate/?distribution=Class-Singleton>.
227
229 The latest version of this module is available from CPAN (see "CPAN" in
230 perlmodlib for details) at
231
232 <https://metacpan.org/release/Class-Singleton> or
233
234 <https://www.cpan.org/authors/id/S/SH/SHAY/> or
235
236 <https://www.cpan.org/modules/by-module/Class/>.
237
238 The latest source code is available from GitHub at
239 <https://github.com/steve-m-hay/Class-Singleton>.
240
242 See the INSTALL file.
243
245 Andy Wardley <abw@wardley.org <mailto:abw@wardley.org>>
246 <http://wardley.org/>.
247
248 Thanks to Andreas Koenig for providing some significant speedup patches
249 and other ideas.
250
251 Steve Hay <shay@cpan.org <mailto:shay@cpan.org>> is now maintaining
252 Class::Singleton as of version 1.5.
253
255 Copyright (C) 1998 Canon Research Centre Europe Ltd.
256
257 Copyright (C) 1998-2008 Andy Wardley. All rights reserved.
258
259 Copyright (C) 2014, 2020 Steve Hay. All rights reserved.
260
262 This module is free software; you can redistribute it and/or modify it
263 under the same terms as Perl itself, i.e. under the terms of either the
264 GNU General Public License or the Artistic License, as specified in the
265 LICENCE file.
266
268 Version 1.6
269
271 02 Dec 2020
272
274 See the Changes file.
275
276
277
278perl v5.36.0 2023-01-20 Class::Singleton(3)