Aspect::Library::Singleton - A singleton aspect


Aspect documentation Contained in the Aspect distribution.

Index


Code Index:

NAME

Top

Aspect::Library::Singleton - A singleton aspect

SYNOPSIS

Top

  use Aspect;
  use Aspect::Singleton;

  aspect Singleton => 'Foo::new';

  my $f1 = Foo->new;
  my $f2 = Foo->new;

  # Both $f1 and $f2 refer to the same object

DESCRIPTION

Top

A reusable aspect that forces singleton behavior on a constructor. The constructor is defined by a pointcut spec: a string. regexp, or code ref.

It is slightly different from Class::Singleton (http://search.cpan.org/~abw/Class-Singleton/Singleton.pm):

Note that this is just a special case of memoizing.

AUTHORS

Top

Adam Kennedy <adamk@cpan.org>

Marcel Grünauer <marcel@cpan.org>

Ran Eilam <eilara@cpan.org>

COPYRIGHT

Top


Aspect documentation Contained in the Aspect distribution.

package Aspect::Library::Singleton;

use strict;
use warnings;
use Aspect::Modular        ();
use Aspect::Advice::Before ();
use Aspect::Pointcut::Call ();

our $VERSION = '1.01';
our @ISA     = 'Aspect::Modular';

my %CACHE = ();

sub get_advice {
	my $self = shift;
	Aspect::Advice::Around->new(
		lexical  => $self->lexical,
		pointcut => Aspect::Pointcut::Call->new(shift),
		code     => sub {
			my $class = $_->self;
			$class    = ref $class || $class;
			if ( exists $CACHE{$class} ) {
				$_->return_value($CACHE{$class});
			} else {
				$_->proceed;
				$CACHE{$class} = $_->return_value;
			}
		},
	);
}

1;

__END__