title: How can I create an object whose derived class is specified implicitly by the creation properties?
body: <p>I'm looking for a pattern for the following. (I'm working in Perl, but I don't think the language matters particularly).</p>
  
  <p>With a parent class Foo, and children Bar, Baz, Bazza. </p>
  
  <p>One of the methods for constructing a Foo is by parsing a string, and part of that string will implicitly specify which class is to be created. So for example if it starts 'http:' then it's a Bar, but if it doesn't but it contains '[Date]' then Baz likes it, and so on.</p>
  
  <p>Now, if Foo knows about all its children, and what string is a Bar, what is a Baz etc, it can call the appropriate constructor. But a base class should not have any knowledge about its children.</p>
  
  <p>What I want is for Foo's constructor to be able to try its children in turn, until one of them says "Yes, this is mine, I'll create the thing". </p>
  
  <p>I realise that in the general case this problem is not well-defined, as there may be more than one child which will accept the string, and so the order in which they are called matters: ignore this and assume that the characteristics of the string are such that only one child class will like the string.</p>
  
  <p>The best I have come up with is for the child classes to 'register' with the base class on initialisation, so that it gets a list of constructors, and then loop through them. But is there a better method that I'm missing?</p>
  
  <p>Sample code:</p>
  
  <pre><code>package Foo;
  
  my @children;
  
  sub _registerChild
  {
    push @children, shift();
  }
  
  sub newFromString
  {
    my $string = shift;
    foreach (@children) {
      my $object = $_-&gt;newFromString(@_) and return $object;
    }
    return undef;
  }
  
  package Bar;
  our @ISA = ('Foo');
  
  Foo::_registerChild(__PACKAGE__);
  
  sub newFromString
  {
    my $string = shift;
    if ($string =~ /^http:/i) {
      return bless(...);
    }
    return undef;
  }
  </code></pre>