package Xyzzy; { # scope of cache my $cached = {}; sub instance { my $class = shift; # may be a derived subclass my @args = @_; # reuse singleton object iff a valid one is available. delete $cached->{$class} if ($class->cache_invalid()); return $cached->{$class} if ($cached->{$class}); # no object in the cache, so create/return a new one. my $obj = new $class( @args ); $cached->{$class} = $obj; return $obj; } } # scope of cache sub new { my $class = shift; my @args = @_; my $obj = {}; bless( $obj, $class ); $obj->_initialize( @args ); # expensive! return $obj; }