PerlingTheUK has asked for the wisdom of the Perl Monks concerning the following question:
within a subclass. Do I miss out any problems when I just replace $singleton by a hash which includes the classname:package Singleton; my $singleton; sub new { my $class = shift; $singleton ||= bless {}, $class; }
The actual base class would look something like this:package SingletonBase; my $singleton; sub new { my $class = shift; $singleton{ $class } ||= bless {}, $class; }
I have added the functions _get, _create and %_singleton in the closure as well as changed the lines above and below the bless statement. Do I miss anything out? Are there any big setbacks? It seems too easy to me. Would it for some reason be a lot better to go via getInstance methods? Thank you for all help. PerlingTheUK# encapsulated class data { my %_singleton; my %_attr_data = ( _dbd => [ undef, 'r/w' ], _dbname => [ undef, 'r/w' ], _dbpass => [ undef, 'r/w' ], _dbserver => [ undef, 'r/w' ] ); my $_count = 0; sub _get { my ( $class ) = @_; return $_singleton{ $class } if ( $defined( _singleton{ $class } ) + ); return 0; } sub _create { my ( $self ) = @_; my $_singleton{ ref($self) } = $self; } sub _accessible { my ( $self, $attr, $mode ) = @_; $_attr_data{$attr}[1] =~ /$mode/; } sub _default_for { my ( $self, $attr ) = @_; $_attr_data{$attr}[0]; } sub _standard_keys { keys %_attr_data } sub _count { my ( $self ) = @_; ++$_count; $self->{ "_id" } = $_count; } } sub new { my ( $caller, %arg ) = @_; my $caller_is_obj = ref( $caller ); my $class = $caller_is_obj || $caller; return _get( $class ) if ( _get( $class ) ); my $self = bless {}, $class; $self->_create(); foreach my $attrname ( $self->_standard_keys() ) { my ( $argname ) = ( $attrname =~ /^_(.*)/ ); if ( exists $arg{ $argname } ) { $self->{ $attrname } = $arg{ $argname } } elsif ( $caller_is_obj ) { $self->{ $attrname } = $caller->{ $attrname } } else { $self->{ $attrname } = $self->_default_for( $attrname ) } } $self->_count(); return $self; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Singletons and Inheritance
by Joost (Canon) on Jul 20, 2004 at 11:12 UTC | |
by PerlingTheUK (Hermit) on Jul 20, 2004 at 11:21 UTC | |
by Joost (Canon) on Jul 20, 2004 at 11:28 UTC | |
|
Re: Singletons and Inheritance
by gellyfish (Monsignor) on Jul 20, 2004 at 11:13 UTC | |
|
Re: Singletons and Inheritance
by gaal (Parson) on Jul 20, 2004 at 11:17 UTC | |
by PerlingTheUK (Hermit) on Jul 20, 2004 at 12:53 UTC | |
by gaal (Parson) on Jul 20, 2004 at 13:22 UTC | |
|
Re: Singletons and Inheritance
by adrianh (Chancellor) on Jul 20, 2004 at 13:40 UTC | |
|
Re: Singletons and Inheritance
by bean (Monk) on Jul 20, 2004 at 21:29 UTC | |
|
Re: Singletons and Inheritance
by clscott (Friar) on Jul 21, 2004 at 20:55 UTC | |
by PerlingTheUK (Hermit) on Jul 22, 2004 at 07:26 UTC |