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

时间:2016-07-13 18:03:40

标签: php class polymorphism subclass abstract

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

例如,我有一个User类,其中包含方法get_membership(),该方法将根据传递的成员资格类型返回子类。我目前正在使用switch语句来返回正确的子类,但是我不相信这是最好的方法。

我和我的简短例子。使用:

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;
  }
}

1 个答案:

答案 0 :(得分:0)

有条件地实例化正确的子类是可以的,但通常建议将此逻辑分成另一个类/方法,称为factory。事实上,这是一个非常常见的design pattern

相关问题