| 1 | #======================================================================== | ||
| 2 | # | ||
| 3 | # Badger::Prototype | ||
| 4 | # | ||
| 5 | # DESCRIPTION | ||
| 6 | # Base class module for a protoype class that has a default instance | ||
| 7 | # that can be created on demand. | ||
| 8 | # | ||
| 9 | # AUTHOR | ||
| 10 | # Andy Wardley <abw@wardley.org> | ||
| 11 | # | ||
| 12 | #======================================================================== | ||
| 13 | |||
| 14 | package Badger::Prototype; | ||
| 15 | |||
| 16 | use Badger::Class | ||
| 17 | base => 'Badger::Base', | ||
| 18 | version => 0.01, | ||
| 19 | debug => 0, | ||
| 20 | constants => 'PKG REFS ONCE', | ||
| 21 | words => 'PROTOTYPE'; | ||
| 22 | |||
| 23 | sub prototype { | ||
| 24 | my $class = shift; | ||
| 25 | return $class if ref $class; | ||
| 26 | no strict REFS; | ||
| 27 | no warnings ONCE; | ||
| 28 | |||
| 29 | if (@_ == 1 && ! defined $_[0]) { | ||
| 30 | # if only a single undef argument is provided, then clear any | ||
| 31 | # prototype from $PROTOTYPE and return a reference to it. | ||
| 32 | my $proto = ${$class.PKG.PROTOTYPE}; | ||
| 33 | undef ${$class.PKG.PROTOTYPE}; | ||
| 34 | return $proto; | ||
| 35 | } | ||
| 36 | elsif (@_) { | ||
| 37 | # if any other arguments are provided then it forces us to create | ||
| 38 | # a new prototype with the fresh configuration options. | ||
| 39 | undef ${$class.PKG.PROTOTYPE}; | ||
| 40 | } | ||
| 41 | |||
| 42 | # return the cached value (assuming we didn't just clear it) or create | ||
| 43 | # a new one (if we did, or if there wasn't a previous value) | ||
| 44 | return ${$class.PKG.PROTOTYPE} ||= $class->new(@_); | ||
| 45 | } | ||
| 46 | |||
| 47 | sub has_prototype { | ||
| 48 | my $self = shift; | ||
| 49 | my $class = ref $self || $self; | ||
| 50 | no strict REFS; | ||
| 51 | no warnings ONCE; | ||
| 52 | defined ${$class.PKG.PROTOTYPE}; | ||
| 53 | } | ||
| 54 | |||
| 55 | |||
| 56 | 1; | ||
| 57 | |||
| 58 | __END__ |