Home  >  Article  >  php教程  >  Implementing Factory mode in PHP

Implementing Factory mode in PHP

黄舟
黄舟Original
2016-12-21 10:55:451535browse

There is a point of view: There seems to be no such thing as "Factory Pattern". Among the 23 patterns in GoF, there are two related to Factory: Factory Method and Abstract Factory. A Simple Factory pattern is defined in "Introduction to Design Patterns in a Simple Way". I (Hick) looked through the relevant information, and Robert C. Martin's "Agile Software Development: Principles, Patterns, and Pracitces" directly mentioned the "Factory mode". If you are interested in the specific situation, you can check it in detail.

"Factory pattern allows us to create instances of specific objects by relying on abstract interfaces", which is the embodiment of DIP (Dependency Inversion Principle). We can produce different but similar products (instantiated objects) by giving different requirements to a factory.

Hey, people say that the best documentation is code. I not only say this, I can also prove it to you (the display effect here is not good, it is recommended to copy it to the PHP editor to view), the following are "PHP Manual", "Core PHP Programming" and "PHP 5 Power" Example analysis of Factory mode in Programming":

<?php
/**
 * factory 模式
 *
 * factory 的概念不像 Singleton 等模式那样, factory 模式比较
 * 灵活。通常根据不同的要求能够"生产不同对象"(实例化类)就可以
 * 归为 factory 模式或者其变体。
 */
 
/**
 * 先用手册中一个简单的例子说明 factory 模式
 *
 * 注意下面这段代码并不可执行,因为需要定义相应的数据库[Driver]类。
 */
 
classDbFactory
{
    // factory 方法
    publicstaticfunctionfactory($type)
    {
        // 注意这里的包含文件应该是相关数据库的[Driver]类
        if(include_once&#39;Drivers/&#39;.$type.&#39;.php&#39;){
            $classname=&#39;Driver_&#39;.$type;
            returnnew$classname;
        }else{
            thrownewException(&#39;Driver not found&#39;);
        }
    }
}
 
// 生成数据库(MySQL)连接对象,
$DbCon=DbFactory::factory(&#39;MySQL&#39;);
// $DbCon = DbFactory::factory(&#39;SQLite&#39;);
 
 
/**
 * "Core PHP Programming" 中的例子
 */
classFactory
{
    private$registeredClasses=array();
    
    staticprivate$instance=NULL;
 
    privatefunction__construct(){}
 
    staticfunctiongetInstance()
    {
        if(self::$instance==NULL)
        {
            self::$instance=newFactory();
        }
        returnself::$instance;
    }
 
    functionregisterClass($id,$creator_func)
    {
        $this->registeredClasses[$id]=$creator_func;
    }
 
    functioncreateObject($id,$args)
    {
        if(!isset($this->registeredClasses[$id]))
        {
            return(NULL);
        }
        return($this->registeredClasses[$id]($args));
    }
}
 
classMyClass
{
    private$created;
    publicfunction__construct()
    {
        $created=time();
    }
 
    publicfunctiongetCreated()
    {
        return($this->created);
    }
}
 
functionMyClassCreator()
{
    return(newMyClass());
}
 
$factory=Factory::getInstance();
$factory->registerClass(1234,"MyClassCreator");
$instance=$factory->createObject(1234,array());
 
 
/**
 * "PHP 5 Power Programming" 中的对 factory 模式的诠释
 *
 * 一个 Factory 类通常都有一个方法负责接受参数,根据参数的不同来决定
 * "生产"哪个类的实例。下面拿网站的用户作为例子,作为实际运用:把网站
 * 用户分成匿名用户,普通(注册)用户,管理员。我们在类中进行用户的权限
 * 控制---这样能够更好的展现 factory 类在整个类体系中所扮演的角色。
 */
 
/**
 * 基类 User
 */
abstractclassUser
{
    public$name=null;
    
    publicfunction__construct($name)
    {
        $this->name=$name;
    }
    
    functiongetName()
    {
        return$this->name;
    }
    
  // 权限控制方法
    functionhasReadPermission()
    {
        returntrue;
    }
    
    functionhasModifyPermission()
    {
        returnfalse;
    }
    
    functionhasDeletePermission()
    {
        returnfalse;
    }
}
 
// 匿名用户类
classGuestUserextendsUser
{}
 
// 注册用户类
classCustomerUserextendsUser
{
  functionhasModifyPermission()
    {
        returntrue;
    }
}
 
// 管理员类
classAdminUserextendsUser{
  functionhasModifyPermission()
    {
        returntrue;
    }
 
    functionhasDeletePermission()
    {
        returntrue;
    }
}
 
/**
 * 用户 factory 类
 */
classUserFactory{
    privatestatic$users=
        array("Andi"=>"admin","Hick"=>"guest",
                "Derick"=>"customer");
 
    staticfunctionCreate($name)
    {
        if(!isset(self::$users[$name])){
            // 如果不存在对应的用户类,则提示错误
        }
        switch(self::$users[$name]){
            case"guest":returnnewGuestUser($name);
            case"customer":returnnewCustomerUser($name);
            case"admin":returnnewAdminUser($name);
            default:// 默认应该报错
        }
    }
}
 
// 使用 factory 类实例化用户
$HickUser=UserFactory::Create(&#39;Hick&#39;);
echo$HickUser->name;
?>

The above is the content of implementing Factory mode in PHP. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn