工厂模式是指创建一个类似于工厂的类,通过对类中成员方法的调用返回不同类型的对象。
工厂模式通常创建一个基类,根据对象类型的不同创建不同的扩展类,而工厂类就像生产零件一样,生产出类型不同的对象。在程序中,通过对对象的调用实现不同的功能。
一下代码实现了一个管理系统的例子:
<?php
abstract class User
{
provite $name = NULL;
function User($name)
{
$this->name = $name;
}
function getName(){return $this->name;}
function ViewAccess(){return "No";}
function EditAccess(){return "No";}
function DeleteAccess(){return "No";}
function ManageAccess(){return "No";}
}
//普通用户
class Client extends User
{
function ViewAccess()
{
return "Yes";
}
}
class Administrator extends User
{
function ViewAccess(){return "Yes";}
function EditAccess(){return "Yes";}
function DeleteAccess(){return "Yes";}
}
class Supporter extends User
{
function ViewAccess(){return "Yes";}
function EditAccess(){return "Yes";}
function DeleteAccess(){return "Yes";}
function ManageAccess(){return "Yes";}
}
class Factory
{
private static $users = ("Simon"=>"Client","Elaine"=>"Administrator","Bob"=>"Supporter");
static function Create($name)
{
switch (self::$users[$name])
{
case "Client": return new Client($name);
case "Administrator": return Administrator($name);
case "Supporter": return Supporter($name);
}
}
}
$users = array("Elaine","Simon","Bob");
foreach($users as $user)
{
$obj = Factory::Create($user);
echo $obj->getName()."的权限:\n";
echo "浏览:".$obj->ViewAccess()."\n";
echo "修改:".$obj->EditAccess()."\n";
echo "删除:".$obj->DeleteAccess()."\n";
echo "管理:".$obj->ManageAccess()."\n";
}
?>