Singleton.pm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #============================================================================
  2. #
  3. # Class::Singleton.pm
  4. #
  5. # Implementation of a "singleton" module which ensures that a class has
  6. # only one instance and provides global access to it. For a description
  7. # of the Singleton class, see "Design Patterns", Gamma et al, Addison-
  8. # Wesley, 1995, ISBN 0-201-63361-2
  9. #
  10. # Written by Andy Wardley <[email protected]>
  11. #
  12. # Copyright (C) 1998-2008 Andy Wardley. All Rights Reserved.
  13. # Copyright (C) 1998 Canon Research Centre Europe Ltd.
  14. #
  15. #============================================================================
  16. package Class::Singleton;
  17. require 5.004;
  18. use strict;
  19. use warnings;
  20. our $VERSION = 1.4;
  21. #========================================================================
  22. #
  23. # instance()
  24. #
  25. # Module constructor. Creates an Class::Singleton (or derived) instance
  26. # if one doesn't already exist. The instance reference is stored in the
  27. # _instance variable of the $class package. This means that classes
  28. # derived from Class::Singleton will have the variables defined in *THEIR*
  29. # package, rather than the Class::Singleton package. The impact of this is
  30. # that you can create any number of classes derived from Class::Singleton
  31. # and create a single instance of each one. If the _instance variable
  32. # was stored in the Class::Singleton package, you could only instantiate
  33. # *ONE* object of *ANY* class derived from Class::Singleton. The first
  34. # time the instance is created, the _new_instance() constructor is called
  35. # which simply returns a reference to a blessed hash. This can be
  36. # overloaded for custom constructors. Any addtional parameters passed to
  37. # instance() are forwarded to _new_instance().
  38. #
  39. # Returns a reference to the existing, or a newly created Class::Singleton
  40. # object. If the _new_instance() method returns an undefined value
  41. # then the constructer is deemed to have failed.
  42. #
  43. #========================================================================
  44. sub instance {
  45. my $class = shift;
  46. # already got an object
  47. return $class if ref $class;
  48. # we store the instance in the _instance variable in the $class package.
  49. no strict 'refs';
  50. my $instance = \${ "$class\::_instance" };
  51. defined $$instance
  52. ? $$instance
  53. : ($$instance = $class->_new_instance(@_));
  54. }
  55. #=======================================================================
  56. # has_instance()
  57. #
  58. # Public method to return the current instance if it exists.
  59. #=======================================================================
  60. sub has_instance {
  61. my $class = shift;
  62. $class = ref $class || $class;
  63. no strict 'refs';
  64. return ${"$class\::_instance"};
  65. }
  66. #========================================================================
  67. # _new_instance(...)
  68. #
  69. # Simple constructor which returns a hash reference blessed into the
  70. # current class. May be overloaded to create non-hash objects or
  71. # handle any specific initialisation required.
  72. #========================================================================
  73. sub _new_instance {
  74. my $class = shift;
  75. my %args = @_ && ref $_[0] eq 'HASH' ? %{ $_[0] } : @_;
  76. bless { %args }, $class;
  77. }
  78. 1;
  79. __END__
  80. =head1 NAME
  81. Class::Singleton - Implementation of a "Singleton" class
  82. =head1 SYNOPSIS
  83. use Class::Singleton;
  84. my $one = Class::Singleton->instance(); # returns a new instance
  85. my $two = Class::Singleton->instance(); # returns same instance
  86. =head1 DESCRIPTION
  87. This is the C<Class::Singleton> module. A Singleton describes an object class
  88. that can have only one instance in any system. An example of a Singleton
  89. might be a print spooler or system registry. This module implements a
  90. Singleton class from which other classes can be derived. By itself, the
  91. C<Class::Singleton> module does very little other than manage the instantiation
  92. of a single object. In deriving a class from C<Class::Singleton>, your module
  93. will inherit the Singleton instantiation method and can implement whatever
  94. specific functionality is required.
  95. For a description and discussion of the Singleton class, see
  96. "Design Patterns", Gamma et al, Addison-Wesley, 1995, ISBN 0-201-63361-2.
  97. =head1 PREREQUISITES
  98. C<Class::Singleton> requires Perl version 5.004 or later. If you have an older
  99. version of Perl, please upgrade to latest version, available from your nearest
  100. CPAN site (see L<INSTALLATION> below).
  101. =head1 INSTALLATION
  102. The C<Class::Singleton> module is available from CPAN. As the 'perlmod' man
  103. page explains:
  104. CPAN stands for the Comprehensive Perl Archive Network.
  105. This is a globally replicated collection of all known Perl
  106. materials, including hundreds of unbunded modules.
  107. [...]
  108. For an up-to-date listing of CPAN sites, see
  109. http://www.perl.com/perl/ or ftp://ftp.perl.com/perl/ .
  110. The module is available in the following directories:
  111. /modules/by-module/Class/Class-Singleton-<version>.tar.gz
  112. /authors/id/ABW/Class-Singleton-<version>.tar.gz
  113. C<Class::Singleton> is distributed as a single gzipped tar archive file:
  114. Class-Singleton-<version>.tar.gz
  115. Note that "<version>" represents the current version number, of the
  116. form "C<1.23>". See L<VERSION> below to determine the current version
  117. number for C<Class::Singleton>.
  118. Unpack the archive to create an installation directory:
  119. gunzip Class-Singleton-<version>.tar.gz
  120. tar xvf Class-Singleton-<version>.tar
  121. 'cd' into that directory, make, test and install the module:
  122. cd Class-Singleton-<version>
  123. perl Makefile.PL
  124. make
  125. make test
  126. make install
  127. The 'C<make install>' will install the module on your system. You may need
  128. root access to perform this task. If you install the module in a local
  129. directory (for example, by executing "C<perl Makefile.PL LIB=~/lib>" in the
  130. above - see C<perldoc MakeMaker> for full details), you will need to ensure
  131. that the C<PERL5LIB> environment variable is set to include the location, or
  132. add a line to your scripts explicitly naming the library location:
  133. use lib '/local/path/to/lib';
  134. =head1 USING THE CLASS::SINGLETON MODULE
  135. To import and use the C<Class::Singleton> module the following line should
  136. appear in your Perl program:
  137. use Class::Singleton;
  138. The L<instance()> method is used to create a new C<Class::Singleton> instance,
  139. or return a reference to an existing instance. Using this method, it is only
  140. possible to have a single instance of the class in any system.
  141. my $highlander = Class::Singleton->instance();
  142. Assuming that no C<Class::Singleton> object currently exists, this first call
  143. to L<instance()> will create a new C<Class::Singleton> and return a reference
  144. to it. Future invocations of L<instance()> will return the same reference.
  145. my $macleod = Class::Singleton->instance();
  146. In the above example, both C<$highlander> and C<$macleod> contain the same
  147. reference to a C<Class::Singleton> instance. There can be only one.
  148. =head1 DERIVING SINGLETON CLASSES
  149. A module class may be derived from C<Class::Singleton> and will inherit the
  150. L<instance()> method that correctly instantiates only one object.
  151. package PrintSpooler;
  152. use base 'Class::Singleton';
  153. # derived class specific code
  154. sub submit_job {
  155. ...
  156. }
  157. sub cancel_job {
  158. ...
  159. }
  160. The C<PrintSpooler> class defined above could be used as follows:
  161. use PrintSpooler;
  162. my $spooler = PrintSpooler->instance();
  163. $spooler->submit_job(...);
  164. The L<instance()> method calls the L<_new_instance()> constructor method the
  165. first and only time a new instance is created. All parameters passed to the
  166. L<instance()> method are forwarded to L<_new_instance()>. In the base class
  167. the L<_new_instance()> method returns a blessed reference to a hash array
  168. containing any arguments passed as either a hash reference or list of named
  169. parameters.
  170. package MyConfig;
  171. use base 'Class::Singleton';
  172. sub foo {
  173. shift->{ foo };
  174. }
  175. sub bar {
  176. shift->{ bar };
  177. }
  178. package main;
  179. # either: hash reference of named parameters
  180. my $config = MyConfig->instance({ foo => 10, bar => 20 });
  181. # or: list of named parameters
  182. my $config = MyConfig->instance( foo => 10, bar => 20 );
  183. print $config->foo(); # 10
  184. print $config->bar(); # 20
  185. Derived classes may redefine the L<_new_instance()> method to provide more
  186. specific object initialisation or change the underlying object type (to a list
  187. reference, for example).
  188. package MyApp::Database;
  189. use base 'Class::Singleton';
  190. use DBI;
  191. # this only gets called the first time instance() is called
  192. sub _new_instance {
  193. my $class = shift;
  194. my $self = bless { }, $class;
  195. my $db = shift || "myappdb";
  196. my $host = shift || "localhost";
  197. $self->{ DB } = DBI->connect("DBI:mSQL:$db:$host")
  198. || die "Cannot connect to database: $DBI::errstr";
  199. # any other initialisation...
  200. return $self;
  201. }
  202. The above example might be used as follows:
  203. use MyApp::Database;
  204. # first use - database gets initialised
  205. my $database = MyApp::Database->instance();
  206. Some time later on in a module far, far away...
  207. package MyApp::FooBar
  208. use MyApp::Database;
  209. # this FooBar object needs access to the database; the Singleton
  210. # approach gives a nice wrapper around global variables.
  211. sub new {
  212. my $class = shift;
  213. bless {
  214. database => MyApp::Database->instance(),
  215. }, $class;
  216. }
  217. The C<Class::Singleton> L<instance()> method uses a package variable to store
  218. a reference to any existing instance of the object. This variable,
  219. "C<_instance>", is coerced into the derived class package rather than the base
  220. class package.
  221. Thus, in the C<MyApp::Database> example above, the instance variable would
  222. be:
  223. $MyApp::Database::_instance;
  224. This allows different classes to be derived from C<Class::Singleton> that can
  225. co-exist in the same system, while still allowing only one instance of any one
  226. class to exists. For example, it would be possible to derive both
  227. 'C<PrintSpooler>' and 'C<MyApp::Database>' from C<Class::Singleton> and have a
  228. single instance of I<each> in a system, rather than a single instance of
  229. I<either>.
  230. You can use the L<has_instance()> method to find out if a particular class
  231. already has an instance defined. A reference to the instance is returned or
  232. C<undef> if none is currently defined.
  233. my $instance = MyApp::Database->has_instance()
  234. || warn "No instance is defined yet";
  235. =head1 METHODS
  236. =head2 instance()
  237. This method is called to return a current object instance or create a new
  238. one by calling L<_new_instance()>.
  239. =head2 has_instance()
  240. This method returns a reference to any existing instance or C<undef> if none
  241. is defined.
  242. my $testing = MySingleton1->has_instance()
  243. || warn "No instance defined for MySingleton1";
  244. =head2 _new_instance()
  245. This "private" method is called by L<instance()> to create a new object
  246. instance if one doesn't already exist. It is not intended to be called
  247. directly (although there's nothing to stop you from calling it if you're
  248. really determined to do so).
  249. It creates a blessed hash reference containing any arguments passed to the
  250. method as either a hash reference or list of named parameters.
  251. # either: hash reference of named parameters
  252. my $example1 = MySingleton1->new({ pi => 3.14, e => 2.718 });
  253. # or: list of named parameters
  254. my $example2 = MySingleton2->new( pi => 3.14, e => 2.718 );
  255. It is important to remember that the L<instance()> method will I<only> call
  256. the I<_new_instance()> method once, so any arguments you pass may be silently
  257. ignored if an instance already exists. You can use the L<has_instance()>
  258. method to determine if an instance is already defined.
  259. =head1 AUTHOR
  260. Andy Wardley E<lt>[email protected]<gt> L<http://wardley.org/>
  261. Thanks to Andreas Koenig for providing some significant speedup patches and
  262. other ideas.
  263. =head1 VERSION
  264. This is version 1.4, released September 2007
  265. =head1 COPYRIGHT
  266. Copyright Andy Wardley 1998-2007. All Rights Reserved.
  267. This module is free software; you can redistribute it and/or
  268. modify it under the same terms as Perl itself.
  269. =cut