How to have Moose return a child class instance instead of its own class, for polymorphism

前端 未结 2 1185
心在旅途
心在旅途 2021-01-18 21:53

I want to create a generic class, whose builder would not return an instance of this generic class, but an instance of a dedicated child class.

As Moose does automat

2条回答
  •  半阙折子戏
    2021-01-18 22:33

    No (not directly). In general in Moose, calling CLASS->new where CLASS isa Moose::Object will return an instance of CLASS.

    Can you describe in more detail what you are trying to achieve, and why you think this is what you want? You probably want to build a factory class -- when you call a method on it, it will call the appropriate class's constructor and return that object to you, without you having to be concerned with the particular type you get back:

    package MyApp::Factory::Repository;
    
    sub getFactory
    {
         my ($class, %attrs);
    
         # figure out what the caller wants, and decide what type to return
         $class ||= 'Repository::_Sftp';
         return $class->new(attr1 => 'foo', attr2 => 'bar', %attrs);
    }
    
    my $file = MyApp::Factory::Repository->getFactory(uri=>'sftp://blabla');
    

提交回复
热议问题