发布网友 发布时间:2022-04-29 06:30
共3个回答
懂视网 时间:2022-04-29 10:51
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();//我是羊,我吃草
热心网友 时间:2022-04-29 07:59
<?php热心网友 时间:2022-04-29 09:17
简单工厂模式可用接口去实现!