weixin

PHP设计模式 - 工厂模式

日期: January 12, 2019 分类: Web开发 作者:网站维护人员

以上代码来自《PHP5 权威编程》

理解起来,工厂模式就是用在一个地方生产出对象出来,UserFactory 这个类就是生产对象的地方。

<?php
/**
 * Created by PhpStorm.
 * User: Ac
 * Date: 2019/1/13
 * Time: 10:14
 */

abstract class User {
    function __construct($name){
        $this->name = $name;
    }

    function getName(){
        return $this->name;
    }

    function hasReadPermission(){
        return true;
    }

    function hasModifyPermission(){
        return false;
    }

    function hasDeletePermission(){
        return false;
    }

    function wantsFlashInterface(){
        return true;
    }

    protected $name = NULL;
}

class GuestUser extends User {

}

class CustomerUser extends User {
    function hasModifyPermission(){
        return true;
    }
}

class AdminUser extends User {
    function hasModifyPermission(){
        return true;
    }

    function hasDeletePermission(){
        return true;
    }

    function wantsFlashInterface(){
        return true;
    }
}

class UserFactory {
    private static $user = array("Andi"=>"admin","Stig"=>"guest",
        "Derick"=>"customer");

    static function Create($name){
        if (!isset(self::$user[$name])){
            //
        }

        switch (self::$user[$name]){
            case "guest": return new GuestUser($name);
            case "customer": return new CustomerUser($name);
            case "admin": return new AdminUser($name);
            default: //
        }

    }
}

function boolToStr($a){
    if ($a == true){
        return "true\n";
    }else{
        return "false\n";
    }
}

function displayPermissions(User $obj){
    print $obj->getName()."'s permission\n";
    print "Read: " . boolToStr($obj->hasReadPermission());
    print "Modify: " . boolToStr($obj->hasModifyPermission());
    print "Delete: " . boolToStr($obj->hasDeletePermission());
}

function displayRequirement(User $obj){
    if ($obj->wantsFlashInterface()) {
        print $obj->getName() ."require Flash\n";
    }
}


$logins = array("Andi", "Stig", "Derick");

foreach($logins as $login){
    displayPermissions(UserFactory::Create($login));
    displayRequirement(UserFactory::Create($login));
}
qq