Created
August 9, 2015 17:43
-
-
Save jonathanstowe/13f5361cf6ce74776f48 to your computer and use it in GitHub Desktop.
Singley thing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
role Singleton { | |
my $instance; | |
method new(|c) { | |
if not $instance.defined { | |
$instance = self.bless(|c); | |
} | |
$instance; | |
} | |
} | |
multi sub trait_mod:<is>(Method:D $m, :$single!) { | |
$m.wrap(method ( $self: |c) { | |
my $new-self = $self; | |
if not $new-self.defined { | |
$new-self = $self.new; | |
} | |
callwith($new-self,|c); | |
}); | |
} | |
class Foo does Singleton { | |
has $.foo is rw; | |
method say-foo() is single { | |
say $!foo; | |
} | |
} | |
my $a = Foo.new(foo => "this one"); | |
Foo.say-foo; | |
# vim: expandtab shiftwidth=4 ft=perl6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment