工厂模式

Posted on Posted in php
Tips: 本文创建于2014年4月11日,已超过 2 年,内容或图片可能已经失效!

工厂模式php实例一

[code lang="php"]
<?php
/**
* 工厂方法模式
*/
//抽象产品
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();
}
}
//客户端
class Client {
static function main() {
$s = new Student();
$s->doWork();

$t = new Teacher();
$t->doWork();
}
}
Client::main();
?>

[/code]

工厂模式php实例二

[code lang="php"]
<?php
/**
* 简单工厂模式
*/
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 ();
?>
[/code]

php实现工厂模式

» 转载请注明来源:呢喃 » 工厂模式