Home > php教程 > php手册 > body text

php工厂模式简单使用说明

PHP中文网
Release: 2017-03-18 14:38:49
Original
1784 people have browsed it

本文章来给大家介绍php入门教程之工厂模式哦,工厂模式概念:实例化对象,用工厂方法替代new操作,有需要了解学习的朋友可参考.

工厂模式实例代码:

<?php
//首先定义什么是人类  
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 ) {//判断是否继承自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();  
     
//第三批人了,这次火候掌握的正好,黄色人种(不写黄人,免得引起歧义),备注:RB人不属于此列  
var_dump("nn------------造出的第三批人是这样的:黄色人种-----------------");  
$yellowHuman = HumanFactory::createHuman(new YellowHuman());  
$yellowHuman->cry();  
$yellowHuman->laugh();  
$yellowHuman->talk(); 
?>
Copy after login

相关文章:

PHP工厂模式的三种形式的示例代码详解

浅析php工厂模式

解析PHP工厂模式的好处

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template