0
是否有正確的方式來有條件地實例化某些子類?有條件地實例化正確的子類?
例如,我有一個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;
}
}
謝謝@ dean-fenster,我認爲但不確定。 –