是否有正确的方法来有条件地实例化某些子类?
例如,我有一个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;
}
}