<?php
abstract class User
{
protected $name;
public function __construct($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
public function hasReadPermission()
{
return true;
}
public function hasModifyPermission()
{
return false;
}
public function hasDeletePermission()
{
return false;
}
public function wantsFlashInterface()
{
return true;
}
}
class GuestUser extends User
{
}
class CustomerUser extends User
{
public function hasModifyPermission()
{
return true;
}
}
class AdminUser extends User
{
public function hasModifyPermission()
{
return true;
}
public function hasDeletePermission()
{
return true;
}
function wantsFlashInterface()
{
return false;
}
}
class UserFactory
{
private static $users = ['Andi' => 'admin', 'Stig' => 'guest', 'Derick' => 'customer'];
public static function create($name)
{
if (!isset(self::$users[$name])) {
// 报出错误,因为用户不存在
}
switch (self::$users[$name]) {
case "guest": return new GuestUser($name);
case "customer": return new CustomerUser($name);
case "admin": return new AdminUser($name);
default: //报出错误,因为用户类型不存在
}
}
}
function boolToStr($b)
{
if ($b == true) {
return "Yes\n";
} else {
return "No\n";
}
}
function displayPermissions(User $obj)
{
print $obj->getName() . "'s permissions:\n";
print "Read: " . boolToStr($obj->hasReadPermission());
print "Modify: " . boolToStr($obj->hasModifyPermission());
print "Delete: " . boolToStr($obj->hasDeletePermission());
}
function displayRequirements(User $obj)
{
if ($obj->wantsFlashInterface()) {
print $obj->getName() . " requires Flash\n";
}
}
$logins = ["Andi", "Stig", "Derick"];
foreach ($logins as $login) {
displayPermissions(UserFactory::create($login));
displayRequirements(UserFactory::create($login));
}
PHP 工厂模式
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 因为工作的需要,陆陆续续接触了很不多不同的框架,也慢慢渗透了一些设计模式。当初选择入手php,就是因为脚本语言,简...
- 5.1 循环简介 无 5.2 基本运算符 1.赋值是从右向左进行的,如语句`d=c=b=a=1`,先是 a = 1...