有条件地实例化正确的子类?

Conditionally instantiating correct subclasses?

是否有条件实例化某些子class的正确方法?

例如,我有一个包含方法 get_membership()User class,它将 return 一个基于成员类型的子class它通过了。我目前正在使用 switch 语句 return 正确的子 class,但是我不认为这是最好的方法。

我正在使用的简短示例:

class User
{
  public $user_id;
  public function __construct( $user_id )
  {
   $this->user_id = $user_id;
  }
  public function get_membership( $membership_type = 'annual' ) 
  {
   switch( $membership_type )
   {
     case 'annual':
     return new AnnualMembership( $this->user_id );
     break;

     case 'monthly':
     return new MonthlyMembership( $this->user_id );
     break;
   }
  }
}

abstract class UserMembership
{
  protected $user_id;
  protected $length_in_days;

  public function __construct( $user_id )
  {
    $this->user_id = $user_id;
    $this->setup();
  }

  abstract protected function get_length_in_days();
  abstract protected function setup();

}

class AnnualMembership extends UserMembership
{
  public function setup() {
   $this->length_in_days = 365;
  }

  public function get_length_in_days()
  {
    return $this->length_in_days;
  }
}

class MonthlyMembership extends UserMembership
{
  public function setup() {
   $this->length_in_days = 30;
  }

  public function get_length_in_days()
  {
    return $this->length_in_days;
  }
}

可以有条件地实例化正确的子类,但通常建议将此逻辑分离到不同的 class/method,称为 factory. In fact, this is a very common design pattern