假設我有這個經典的開關,我知道當我們建立類不是一個很好的做法使用開關方法,所以,我怎麼可以重建這個成類沒有使用開關但多態性,我想了解的方法。PHP5 - 面向對象 - 多態 - 幫我改寫這個簡單的開關
/**
* globals below are holding unique id
* $Franklin['Franklin_id'] ,
* $Granny_Smith['Granny_Smith_id'] ,
* etc etc...
*/
global $Fuji, $Gala, $Franklin, $Granny_Smith;
switch($Apple) {
case 'Fuji':
$Color = 'Yellowish green';
$Size = 'medium';
$Origin = 'Japan';
$Season = 'October - January';
$AppleId = $Fuji['Fuji_id'];
break;
case 'Gala':
$Color = 'yellow';
$Size = 'medium';
$Origin = 'New Zealand';
$Season = 'October - January';
$AppleId = $Gala['Gala_id'];
break;
case 'Franklin':
$Color = 'Well-colored';
$Size = 'medium';
$Origin = 'Ohio';
$Season = 'October';
$AppleId = $Franklin['Franklin_id'];
break;
case 'Granny_Smith':
$Color = 'Green';
$Size = 'medium';
$Origin = 'Australia';
$Season = 'October - December';
$AppleId = $Granny_Smith['Granny_Smith_id'];
break;
}
然後我想能夠使用它像這樣
$AppleProps = new getApple('Granny_Smith'); // $AppleProps->Color, etc etc
預先感謝您,希望這可以幫助別人。
親切的問候
盧卡
- 感謝對http://www.allaboutapples.com/爲蘋果信息;)
*(參考)* [更換條件與多態性(http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism) – Gordon 2011-02-17 18:41:12
@Gordon - 謝的好友,這絕對要求第二部分或題。 ;) – 2011-02-17 18:44:02