php设计模式-工厂模式

封装、继承、多态为oop的三大核心特性,我们可以根据这些特性,使用工厂模式。

工厂模式:在有些时候,需要创建基类的子类的一个具体实例,可以通过工厂模式实现,通常一个工厂类拥有一个静态的方法,用来接收一些输入,并根据输入决定创建哪个类的实例(通常是一个子类)

假设,我们有一个这样的需求,网站有3种用户:管理员,会员,游客,这3种用户具有不同的权限和后台管理页面,通常管理员的后台是固定的,游客和会员根据类型调用不同的页面

1,通过oop基本的3大特性,实现用户分层,权限和后台进行定制

 1 abstract class User {
 2     protected $name = NULL;
 3     function __construct( $name ) {
 4         $this->name = $name;
 5     }
 6     function getName(){
 7         return $this->name;
 8     }
 9     function hasReadPermission(){
10         return true;
11     }
12     function hasModifyPermission(){
13         return false;
14     }
15     function hasDeletePermission(){
16         return false;
17     }
18     function wantsFlashInterface(){
19         return true;
20     }
21 }
22 
23 class GuestUser extends User {
24 }
25 
26 class CustomerUser extends User {
27     function hasModifyPermission(){
28         return true;
29     }
30 }
31 
32 class AdminUser extends User {
33     function hasModifyPermission(){
34         return true;
35     }
36     function hasDeletePermission(){
37         return true;
38     }
39     function wantsFlashInterface(){
40         return false;
41     }
42 }

二,通过工厂类控制创建对应的子类实例

class UserFactory {
    private static $users = array( "ghostwu" => "admin", "lisi" => "guest", "wangwu" => "customer" );
    static function create( $name ){
        if( !isset( self::$users[$name] ) ) {
            echo $name . ",这个用户不存在" . PHP_EOL;
            return ;
        }
        switch( self::$users[$name] ){
            case "admin":
                return new AdminUser( $name );
            case "guest":
                return new GuestUser( $name );
            case "customer":
                return new CustomerUser( $name );
            default:
                return "不存在该用户类型";
        }
    }
}

三、结合之前的封装,完善业务

function boolToStr( $b ){
    if( $b == true ){
        return "yes" . PHP_EOL;
    }else {
        return "no" . PHP_EOL;
    }
}

function displayPermissions( User $obj ){
    echo $obj->getName() . ",该用户权限:" . PHP_EOL;    
    echo "read:" .  boolToStr( $obj->hasReadPermission() );
    echo "modify:" . boolToStr( $obj->hasModifyPermission() );
    echo "delete:" . boolToStr( $obj->hasDeletePermission() );
}

function displayRequirements( User $obj ){
    echo "刷新后台界面:" . boolToStr( $obj->wantsFlashInterface() );
}

$logins = array( "ghostwu", "lisi", "wangwu" );
foreach( $logins as $login ) {
    displayPermissions( UserFactory::create( $login ) );
    displayRequirements( UserFactory::create( $login ) );
    echo "----------------------------" . PHP_EOL;
}

 

 

posted @ 2018-02-23 11:23  ghostwu  阅读(385)  评论(0编辑  收藏  举报
Copyright ©2017 ghostwu