Commit | Line | Data |
109b110b |
1 | #!/usr/bin/env perl |
8eec3c69 |
2 | package MooseX::Singleton::Role::Meta::Class; |
3 | use Moose::Role; |
a4e5ec1e |
4 | use MooseX::Singleton::Role::Meta::Instance; |
5 | use MooseX::Singleton::Role::Meta::Method::Constructor; |
109b110b |
6 | |
1de95613 |
7 | sub existing_singleton { |
3822ace2 |
8 | my ($class) = @_; |
9 | my $pkg = $class->name; |
10 | |
11 | no strict 'refs'; |
12 | |
13 | # create exactly one instance |
1de95613 |
14 | if (defined ${"$pkg\::singleton"}) { |
15 | return ${"$pkg\::singleton"}; |
3822ace2 |
16 | } |
17 | |
1de95613 |
18 | return; |
19 | } |
20 | |
03e1b8df |
21 | sub clear_singleton { |
22 | my ($class) = @_; |
23 | my $pkg = $class->name; |
24 | no strict 'refs'; |
25 | undef ${"$pkg\::singleton"}; |
26 | } |
27 | |
0cd38a85 |
28 | override _construct_instance => sub { |
1de95613 |
29 | my ($class) = @_; |
30 | |
31 | # create exactly one instance |
32 | my $existing = $class->existing_singleton; |
33 | return $existing if $existing; |
34 | |
35 | my $pkg = $class->name; |
36 | no strict 'refs'; |
37 | return ${"$pkg\::singleton"} = super; |
3822ace2 |
38 | }; |
39 | |
2b4ce4bd |
40 | no Moose; |
41 | |
109b110b |
42 | 1; |
43 | |
b375b147 |
44 | __END__ |
45 | |
46 | =pod |
47 | |
48 | =head1 NAME |
49 | |
8eec3c69 |
50 | MooseX::Singleton::Role::Meta::Class - Metaclass role for MooseX::Singleton |
b375b147 |
51 | |
52 | =head1 DESCRIPTION |
53 | |
8eec3c69 |
54 | This metaclass role makes sure that there is only ever one instance of an |
55 | object for a singleton class. The first call to C<construct_instance> is run |
56 | normally (and then cached). Subsequent calls will return the cached version. |
b375b147 |
57 | |
58 | =cut |
59 | |