简单工厂模式,又称为静态工厂模式,在其工厂类中通过一个公有的静态方法返回每个类的实例。

代码:

//家禽接口

interface fowl

{

public function eat(){};

public function breed(){};

}


//母鸡类

class hen implements fowl

{

public function eat()

{

echo "我是鸡,我吃稻子和虫子!";

}


public function breed()

{

echo "我会生鸡蛋,咯咯蛋!";

}

}


//鸭子类

class duck implements fowl

{

public function eat()

{

echo "我是鸭子,我要吃鱼!";

}


public function breed()

{

echo "我会生鸭蛋,嘎嘎嘎!";

}

}


class nofowlException extends Exception

{

public $msg;

public $errType;


public function __construct($msg='',$errType=0)

{

$this->msg=$msg;

$this->errType=$errType;

}

}


//饲养员

class breeder

{

public static function factory($fowl)

{

switch($fowl)

{

case 'hen':

return new hen();

break;


case 'duck':

return new duck();

break;


default:

throws new nofowlException('对不起我们暂时还没有养这种家禽');

break;

}

}

}


//主程序

$hen=breeder::factory('hen');

$hen->eat();//输出我是鸡,我吃稻子和虫子!"

$hen->breed();//输出我会生鸡蛋,咯咯蛋!

$duck=breeder::factory('duck');

$duck->eat();//我是鸭子,我要吃鱼!

$duck->breed();//我会生鸭蛋,嘎嘎嘎!

$goose->breeder::factory('goose');//输出对不起我们暂时还没有养这种家禽