展示經典工廠模式在 PHP 中的實作:定義介面 Human、抽象基類 AbstractHuman、三具體子類,以及靜態工廠方法 HumanFactory::createHuman() 統一實例化入口。
<?php
// 1. 介面定義契約
interface Human {
public function laugh();
public function cry();
public function talk();
}
// 2. 抽象基類實作共通邏輯
abstract class AbstractHuman implements Human {
protected $name;
public function __construct($name) { $this->name = $name; }
public function getName() { return $this->name; }
// laugh/cry/talk 由子類實作
}
// 3. 具體實作
class YellowHuman extends AbstractHuman {
public function cry() { echo "黃色人種會哭\n"; }
public function laugh() { echo "黃色人種會大笑,幸福呀!\n"; }
public function talk() { echo "黃色人種會說話,一般說的都是雙字節\n"; }
}
class WhiteHuman extends AbstractHuman { /* ... */ }
class BlackHuman extends AbstractHuman { /* ... */ }
// 4. 工廠類
class HumanFactory {
public static function createHuman($type) {
$class = ucfirst(strtolower($type)) . 'Human'; // 'yellow' → 'YellowHuman'
if (!class_exists($class)) {
throw new Exception("未知人種: $type");
}
$instance = new $class($type);
if (!($instance instanceof Human)) {
throw new Exception("必須實作 Human 介面");
}
return $instance;
}
}
// 5. 使用
$yellow = HumanFactory::createHuman('yellow');
$yellow->cry(); $yellow->laugh(); $yellow->talk();
$white = HumanFactory::createHuman('white');
$white->cry(); $white->laugh(); $white->talk();
?>
GUIFactory 建立 Win/Mac 按鈕、視窗)。