【结构图】
【主要角色】
【工厂模式php实例】
<?php /** * 工厂方法模式 * ------------- * @author zhaoxuejie <[email protected]> * @package design pattern * @version v1.0 2011-12-14 */ //抽象产品 interface Work { public function doWork(); } //详细产品实现 class Student implements Work { function doWork(){ echo "学生做作业!\n"; } } class Teacher implements Work { function doWork(){ echo "老师批改作业!\n"; } } //抽象工厂 interface WorkerFactory { public function getWorker(); } //详细抽象工厂实现 class StudentFactory { function getWorker(){ return new Student(); } } class TeacherFactory { function getWorker(){ return new Teacher(); } } //client class Client { static function main() { $s = new Student(); $s->doWork(); $t = new Teacher(); $t->doWork(); } } Client::main(); ?>
简单工厂模式是由一个工厂对象决定创建出哪一种产品类的实例。简单工厂模式是工厂模式家族中最简单有用的模式,能够理解为是不同工厂模式的一个特殊实现。
【简单工厂模式php实例】
<?php /** * 简单工厂模式 * ------------- * @author zhaoxuejie <[email protected]> * @package design pattern * @version v1.0 2011-12-14 */ interface Comput { public function getResults(); } //操作类 class Operation { protected $Number_A = 0; protected $Number_B = 0; protected $Result = 0; //赋值 function setNumber($Number_A, $Number_B){ $this->Number_A = $Number_A; $this->Number_B = $Number_B; } //清零 function clearResult(){ $this->Result = 0; } } //加法 class OperationAdd extends Operation implements Comput { function getResults(){ return $this->Result = ($this->Number_A + $this->Number_B); } } //减法 class OperationSub extends Operation implements Comput { function getResults(){ return $this->Result = ($this->Number_A - $this->Number_B); } } //乘法 class OperationMul extends Operation implements Comput { function getResults(){ return $this->Result = ($this->Number_A * $this->Number_B); } } //除法 class OperationDiv extends Operation implements Comput { function getResults(){ if(intval($this->Number_B) == 0){ return $this->Result = 'Error: Division by zero'; } return $this->Result = ($this->Number_A / $this->Number_B); } } //工厂 class OperationFactory { private static $obj; public static function CreateOperation($type){ try { $error = "Please input the '+', '-', '*', '/' symbols of Math."; switch($type){ case '+' : self::$obj = new OperationAdd(); break; case '-' : self::$obj = new OperationSub(); break; case '*' : self::$obj = new OperationMul(); break; case '/' : self::$obj = new OperationDiv(); break; default: throw new Exception($error); } return self::$obj; } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; exit; } } } //创建工厂的实例 $obj = OperationFactory::CreateOperation('*'); $obj->setNumber(3, 4); echo $obj->getResults(); ?
>