Home  >  Article  >  Backend Development  >  php simple factory pattern

php simple factory pattern

WBOY
WBOYOriginal
2016-08-08 09:25:18948browse

Simple factory mode example-simple TV factory

//抽象产品类TV
interface TV {
	public function play();
}
//具体产品类HaierTv
class HaierTV implements TV 
{
	public function play() {
		echo '海尔电视机播放中...<br>';
	}
}

//具体产品类HisenseTV
class HisenseTV implements TV 
{
	public function play() {
		echo '海信电视播放中...<br>';
	}
}
class TVFactory
{
	public static function produceTV($name) {
		switch ($name)
		{
			case 'Haier': echo '电视机工厂生产海尔电视机<br>';return new HaierTV();
			case 'Hisense': echo '电视机工厂生产海信电视机<br>';return new HisenseTV();
			default: echo '不能生产该电视机<br>';break;
		}
	}
}
$factory = new TVFactory();
$tvstring = simplexml_load_file('configTV.xml'); 


foreach ($tvstring as $tv ) {
$tmp = $factory->produceTV($tv->name);
if ($tmp != NULL) {
$tmp->play();
}
}

Configuration file configTV.xml
<?xml version="1.0" encoding="UTF-8"?>  
  <TV>  
	  <HaierTV>  
		  <name>Haier</name>   
	  </HaierTV>  
	  <HisenseTV>  
		  <name>Hisense</name>  
	  </HisenseTV> 	  
  </TV>  
running results

The TV factory produces Haier TV
Haier TV is playing...
The TV factory produces Hisense TV
Hisense TV is playing...

The above introduces the PHP simple factory mode, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
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