php 建造者模式

WBOY
Lepaskan: 2016-08-08 09:25:02
asal
1093 orang telah melayarinya

建造者模式-创建套餐

1.产品类Meal(套餐类)

class Meal 
{
	private $food;
	private $drink;
	
	public function setFood($f) {
		$this->food = $f;
	}
	public function setDrink($d) {
		$this->drink = $d;
	}
	
	public function getFood() {
		return $this->food;
	}
	public function getDrink() {
		return $this->drink;
	}
}
Salin selepas log masuk

2.抽象建造者类MealBuilder(套餐建造者类)

abstract class MealBuilder
{
	protected $meal;
	function __construct() {
		$this->meal = new Meal();
	}
	abstract protected function buildFood();
	abstract protected function buildDrink();
	
	public function getMeal() {
		return $this->meal;
	}
}
Salin selepas log masuk

3.具体建造者类SubMealBuilderA(A套餐建造者类)
class SubMealBuilderA extends MealBuilder
{
	public function buildFood() {
		$this->meal->setFood('一个鸡腿堡');
		
	}
	public function buildDrink() {
		$this->meal->setDrink('一杯可乐');
	}
	public function getMeal() {
		return $this->meal;
	}
}
Salin selepas log masuk

4.具体建造者类SubMealBuilderB(B套餐建造者类)
class SubMealBuilderB extends MealBuilder
{
	public function buildFood() {
		$this->meal->setFood('一个鸡肉卷');

	}
	public function buildDrink() {
		$this->meal->setDrink('一杯果汁');
	}
	public function getMeal() {
		return $this->meal;
	}
}
Salin selepas log masuk

5.指挥者类KFCWaiter(服务员类)
class KFCWaiter
{
	private $MealBuilder;
	
	public function setMealBuilder($mb) {
		eval("\$m= new {$mb}();");
		$this->MealBuilder = $m;
		return $this->MealBuilder;
	}
	public function construct() {
		$this->MealBuilder->buildFood();
		$this->MealBuilder->buildDrink();
		return $this->MealBuilder->getMeal();
	}
}
Salin selepas log masuk

6.配置文件
<?xml version="1.0" encoding="UTF-8"?>  
  <meal>  
	  <meala>  
		  <name>SubMealBuilderA</name>   
	  </meala> 
	  <mealb>  
		  <name>SubMealBuilderB</name>   
	  </mealb>  	  
  </meal> 
Salin selepas log masuk

6.辅助测试代码
$mealstring = simplexml_load_file('meal.xml');
$waiter = new KFCWaiter();
foreach ($mealstring as $Submeal) {
	$waiter->setMealBuilder($Submeal->name);
	$meal = $waiter->construct();
	echo '套餐组成:';
	echo "<br>";
	echo $meal->getFood();
	echo "<br>";
	echo $meal->getDrink();
	echo "<br>";
	echo "<br>";
}
Salin selepas log masuk

运行结果

套餐组成:
一个鸡腿堡
一杯可乐
套餐组成:
一个鸡肉卷
一杯果汁

以上就介绍了php 建造者模式,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan