On Sun, Apr 19, 2009 at 4:31 PM, Chris Prather <perig...@gmail.com> wrote:
> Sorry I've been really busy all weekend and not at a computer. Your
> problem is what people in other situations call a Factory Pattern with
> a minor variation. I meant to write a while ago (like I said busy) a
> suggestion of something like:
>
> [...] snip

Gah, I posted saying exactly this, but forgot to use reply all >.<
Anyway, here's what I wrote:

What you're trying to achieve here is usually done by using the
factory design pattern. I would do it something like:

--

package Test::V1;
use Moose;

has 'foo' => ( is => 'rw', default => 1 );

package Test::V2;
use Moose;

has 'foo' => ( is => 'rw', default => 2 );
has 'bar' => ( is => 'rw' );

package Test;
use MooseX::Singleton;

has 'registered_classes' => (
   isa => 'HashRef',
   is  => 'rw',
   # I wouldn't suggest using builder, but rather
   # MooseX::AttributeHelpers and adding methods like
   # "register_class"
   builder => '_default_classes'
);

sub _default_classes {
   return {
       1 => "Test::V1",
       2 => "Test::V2"
   }
}

sub create {
   my ($self, $ver, @args) = @_;
   my $class = $self->registered_classes->{$ver}
       or return;
   return $class->new(@args);
}

use Test;

my $foo  = Test->create(1);
my $foo2 = Test->create(2, bar => 'yay');

printf "\$foo isa %s\n", $foo->meta->class->name;
printf "\$foo2 isa %s\n", $foo2->meta->class->name;

---

Untested code, but hopefully you get the general idea.

-- 
    Oliver Charles / aCiD2

Reply via email to