本文章来给大家介绍php入门教程之工厂模式哦,工厂模式概念:实例化对象,用工厂方法替代new操作,有需要了解学习的朋友可参考.
工厂模式实例代码:
-
- interface Human {
-
- public function laugh();
-
- public function cry();
-
- public function talk();
- }
-
- class YellowHuman implements Human {
- function cry() { var_dump( "黄色人种会哭");}
- function laugh() {var_dump( "黄色人种会大笑,幸福呀!");}
- function talk() {var_dump( "黄色人种会说话,一般说的都是双字节"); }
- }
- class WhiteHuman implements Human {
- public function cry() {var_dump("白色人种会哭");}
- public function laugh() {var_dump("白色人种会大笑,侵略的笑声"); }
- public function talk() {var_dump("白色人种会说话,一般都是但是单字节!"); }
- }
- class BlackHuman implements Human {
- public function cry() {var_dump("黑色人种会哭");}
- public function laugh() {var_dump("黑色人种会大笑,侵略的笑声"); }
- public function talk() {var_dump("黑色人种会说话,一般都是但是单字节!"); }
- }
-
- class HumanFactory {
-
- public static function createHuman( $c ){
- if ($c instanceof Human ) {
- return $c;
- }else {
- var_dump("必须跟HuMan有一腿");
- }
- }
- }
-
- var_dump("------------造出的第一批人是这样的:白人-----------------");
- $whiteHuman = HumanFactory::createHuman( new WhiteHuman());
- $whiteHuman->cry();
- $whiteHuman->laugh();
- $whiteHuman->talk();
-
-
- var_dump("nn------------造出的第二批人是这样的:黑人-----------------");
- $blackHuman = HumanFactory::createHuman(new BlackHuman());
- $blackHuman->cry();
- $blackHuman->laugh();
- $blackHuman->talk();
-
-
- var_dump("nn------------造出的第三批人是这样的:黄色人种-----------------");
- $yellowHuman = HumanFactory::createHuman(new YellowHuman());
- $yellowHuman->cry();
- $yellowHuman->laugh();
- $yellowHuman->talk();