PHP程式碼實現簡單的工廠模式方法
1、定義抽象基礎類別
//家禽類 abstract class Fowl { abstract public function eat();//吃方法 }
2、定義子類
//牛類 class Cattle extends Fowl { public function eat() { echo "我是牛,我吃草"; } } //鴨類 class Duck extends Fowl { public function eat() { echo "我是鴨,我吃魚"; } } //羊類 class Sheep extends Fowl { public function eat() { echo "我是羊,我吃草"; } }
3、工廠類
//工廠類 class Factory { public static function create($fowlName) { switch ($fowlName) { case 'Cattle': return new Cattle(); break; case 'Duck': return new Duck(); break; case 'Sheep': return new Sheep(); break; } } }
4、用戶端
$cattle = Factory::create('Cattle'); $cattle->eat();//我是牛,我吃草 $duck = Factory::create('Duck'); $duck->eat();//我是鴨,我吃魚 $sheep = Factory::create('Sheep'); $sheep->eat();//我是羊,我吃草
以上就是用PHP程式碼實現簡單的工廠模式的詳細內容,更多請關注TW511.COM其它相關文章!