螃蟹学PHP设计模式之工厂模式

7.工厂模式

昨天晚上公司开会,回去都十一点了,原本打算昨天解决的工厂模式留到今天了,下午还得去跑工商局,希望创业之路顺利吧。螃蟹觉得工厂模式应该是使用比较多的,但是要和建造者模式区分开,建造者是原对象不确定,而工厂模式是同一类的对象有多个。螃蟹还是用比喻来说明,你要生产手机,要做手机肯定要先做一个模型,然后根据模型来生产各种贴牌手机,然后山寨大王由此诞生。其实之前学的委托模式和这个比较像,不过委托模式对对象的控制更多一些,工厂模式只是用于生产对象,不做其他的控制,而且对象的类别是一样的。

参考项目模块:道具系统

虽然螃蟹没开发游戏,但是一般网络游戏都有道具商店,而道具一般都会增加,这个螃蟹觉得是利用工厂模式极好的例子。下面螃蟹就来实现一个简单的道具系统,

首先创建道具基类:BaseProp.php

<?php
class BaseProp{
	protected $_name = null;
	protected $_description = null;
	protected $_price = 0; //售价
	protected $_physical = 0; //体力变化
	protected $_damage = 0; //攻击变化

	/**
	 * @return the $_name
	 */
	public function getName() {
		return $this->_name;
	}

	/**
	 * @return the $_description
	 */
	public function getDescription() {
		return $this->_description;
	}

	/**
	 * @return the $_price
	 */
	public function getPrice() {
		return $this->_price;
	}

	/**
	 * @return the $_physical
	 */
	public function getPhysical() {
		return $this->_physical;
	}

	/**
	 * @return the $_damage
	 */
	public function getDamage() {
		return $this->_damage;
	}
	
	public function getProp(){
		$prop = array();
		$prop['name'] = $this->_name;
		$prop['description'] = $this->_description;
		$prop['price'] = $this->_price;
		$prop['physical'] = $this->_physical;
		$prop['damage'] = $this->_damage;
		return $prop;
	}
}

基类包含了道具的各个基本属性和方法,然后创建道具对象:

铜道具对象:Copper.Prop.php

<?php
require_once('BaseProp.php');

class CopperProp extends BaseProp{
	function __construct(){
		$this->_name = '铜';
		$this->_description = '使用本催化剂,能提高攻击力';
		$this->_price = 50; //售价
		$this->_physical = 50; //生命力变化
		$this->_damage = 200; //攻击力变化
	}
}

金道具对象:Gold.Prop.php

<?php
require_once('BaseProp.php');

class GoldProp extends BaseProp{
	function __construct(){
		$this->_name = '金';
		$this->_description = '使用本催化剂,能提高生命力';
		$this->_price = 150; //售价
		$this->_physical = 300; //生命力变化
		$this->_damage = 90; //攻击力变化
	}
}

再定义一个道具工厂类,用来生产道具对象:FactoryProp.php

<?php 
class FactoryProp{
	public static function create($prop_type){
		$class_file = $prop_type.'.Prop.php';
		require_once($class_file);
		$class_obj = $prop_type.'Prop';
		return new $class_obj;
	}
}
?>

好,最后仍是不厌其烦的测试类:TestFacory.php

<?php 
require('FactoryProp.php');
//模拟道具数组
$prop_type = array('Copper','Gold');
//循环输出
foreach($prop_type as $k => $v){
	$prop = FactoryProp::create($v);
	print_r($prop->getProp());
	echo '<br>';
}
?>

输出结果:

Array ( [name] => 铜 [description] => 使用本催化剂,能提高攻击力 [price] => 50 [physical] => 50 [damage] => 200 ) 
Array ( [name] => 金 [description] => 使用本催化剂,能提高生命力 [price] => 150 [physical] => 300 [damage] => 90 )

使用工厂模式对于大规模对象的处理是很好的和必要的,感觉软件设计的逻辑思维真的很了不起,螃蟹不太喜欢称程序员为码农,作为开发工程师,应该是多think&created,而不是用固化的思维去流水线生产代码和产品。再等一会就可以吃饭了......

你可能感兴趣的:(设计模式,PHP,工厂模式)