Skip to content

Instantly share code, notes, and snippets.

@jonathanstowe
Created August 9, 2015 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanstowe/13f5361cf6ce74776f48 to your computer and use it in GitHub Desktop.
Save jonathanstowe/13f5361cf6ce74776f48 to your computer and use it in GitHub Desktop.
Singley thing
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