Home >Backend Development >PHP Tutorial >PHP development mode factory mode

PHP development mode factory mode

高洛峰
高洛峰Original
2016-12-17 11:12:172103browse

// 开发模式之工程模式
// 工厂模式:
// 由工厂类根据参数来决定创建出哪一种产品类的实例;
// 工厂类是指包含了一个专门用来创建其他对象的方法的类。所谓按需分配,传入参数进行选择,返回具体的类。
// 工厂模式的最主要作用就是对象创建的封装、简化创建对象操作。 
// 简单的说,就是调用工厂类的一个方法(传入参数)来得到需要的类;


//示例1 最基本的工厂模式

class Myname{
	public function OutPutMyName(){
		return 'name is rongyouyuan!~';
	}
}
class NameFactory{
	public static function Namefunc(){
		return new Myname();
	}
}
$obj=NameFactory::Namefunc();
echo $obj->OutPutMyName();
?>

The above is the simplest factory pattern. The following uses the factory pattern to implement a simple calculator

<?php
//定义一个抽象类
abstract class operation
{
    protected $_numA = 0;
    protected $_numB = 0;
    protected $_result = 0;
    public function __construct($a, $b)
    {
        $this->_numA = $a;
        $this->_numB = $b;
    }
    //抽象方法所有子类必须实现该方法
    protected abstract function getResult();
}
//加法运算
class operationAdd extends operation
{
    public function getResult()
    {
        $this->_result = $this->_numA + $this->_numB;
        return $this->_result;
    }
}
//减法运算
class operationSub extends operation
{
    public function getResult()
    {
        $this->_result = $this->_numA - $this->_numB;
        return $this->_result;
    }
}
//乘法运算
class operationMul extends operation
{
    public function getResult()
    {
        $this->_result = $this->_numA * $this->_numB;
        return $this->_result;
    }
}
//除法运算
class operationDiv extends operation
{
    public function getResult()
    {
        $this->_result = $this->_numA / $this->_numB;
        return $this->_result;
    }
}
//定义工厂类
class operationFactory
{
    //创建保存示例的静态成员变量
    private static $obj;
    //创建实例的静态方法
    public static function CreateOperation($type, $a, $b)
    {
        switch ($type) {
        case &#39;+&#39;:
            self::$obj = new operationAdd($a, $b);
            break;
        case &#39;-&#39;:
            self::$obj = new operationSub($a, $b);
            break;
        case &#39;*&#39;:
            self::$obj = new operationMul($a, $b);
            break;
        case &#39;/&#39;:
            self::$obj = new operationDiv($a, $b);
            break;
        }
        //最后返回这个实例
        return self::$obj;
    }
}
//最后我们使用工厂模式
$obj = operationFactory::CreateOperation(&#39;+&#39;, 100, 20);
echo $obj->getResult();

Finally, abstract factory

Definition: Provides an interface for creating a set of related or interdependent objects without specifying their Concrete class.

Type: Create class pattern

Class diagram:

PHP development mode factory mode

The difference between abstract factory pattern and factory method pattern

                                                                                                          -                                                                                            to be created

object. The difference between it and the factory method pattern is that the factory method pattern targets a product hierarchical structure; while the abstract factory pattern targets multiple product hierarchical structures. In programming, usually a product structure is represented by an interface or abstract class. That is to say, all products provided by the factory method pattern are derived from the same interface or abstract class, while the products provided by the abstract factory pattern are derived from from different interfaces or abstract classes.

                     In the abstract factory pattern, there is a concept of product family: the so-called product family refers to a family of functionally related products located in different product hierarchical structures. The series of products provided by the abstract factory pattern form a product family; while the series of products provided by the factory method are called a hierarchical structure. We still use the example of car production to illustrate the differences between them. PHP development mode factory mode

In the above class diagram, hatchbacks and sedans are called two different hierarchical structures; while 2.0-displacement cars and 2.4-displacement cars are called two different product families. To be more specific, 2.0-displacement hatchbacks and 2.4-displacement hatchbacks belong to the same level structure, 2.0-displacement sedans and 2.4-displacement sedans belong to another level structure; and 2.0-displacement hatchbacks and 2.0-displacement sedans belong to another level structure; The sedan belongs to the same product family, and the 2.4-displacement hatchback and the 2.4-displacement sedan belong to another product family.

                                                                                               can understand the difference between the factory method pattern and the abstract factory pattern. If the products of the factory all belong to the same hierarchical structure, it belongs to the factory method pattern; if the products of the factory come from multiple levels Structure, it belongs to the abstract factory pattern. In this example, if a factory model provides 2.0-displacement hatchbacks and 2.4-displacement hatchbacks, then it belongs to the factory method model; if a factory model provides two products: 2.4-displacement hatchbacks and 2.4-displacement sedans , then this factory pattern is the abstract factory pattern, because the products it provides belong to two different hierarchical structures. Of course, if a factory provides products for all four models, because the products belong to two hierarchical structures, it certainly also belongs to the abstract factory model.的 The advantages of the abstract factory model.

In addition to the advantages of the factory method model, the most important advantage is that it can restrain the product family in the class. The so-called product families generally have certain correlations more or less. The abstract factory pattern can define and describe the correlations of product families within the class without having to introduce a new class for management.

Disadvantages of the abstract factory pattern

The expansion of the product family will be a very laborious task. If a new product needs to be added to the product family, almost all factory classes will need to be modified. Therefore, when using the abstract factory pattern, it is very important to divide the product hierarchy.

Applicable Scenarios

When the objects that need to be created are a series of interrelated or interdependent product families, you can use the abstract factory pattern. To put it more clearly, in an inheritance system, if there are multiple hierarchical structures (that is, there are multiple abstract classes), and there are certain associations or constraints between the implementation classes belonging to each hierarchical structure, then You can use the abstract factory pattern. If there are no relationships or constraints between implementation classes in each hierarchical structure, it is more appropriate to use multiple independent factories to create products.

Summary

       无论是简单工厂模式,工厂方法模式,还是抽象工厂模式,他们都属于工厂模式,在形式和特点上也是极为相似的,他们的最终目的都是为了解耦。在使用时,我们不必去在意这个模式到底工厂方法模式还是抽象工厂模式,因为他们之间的演变常常是令人琢磨不透的。经常你会发现,明明使用的工厂方法模式,当新需求来临,稍加修改,加入了一个新方法后,由于类中的产品构成了不同等级结构中的产品族,它就变成抽象工厂模式了;而对于抽象工厂模式,当减少一个方法使的提供的产品不再构成产品族之后,它就演变成了工厂方法模式。

       所以,在使用工厂模式时,只需要关心降低耦合度的目的是否达到了。

<?php
 /** 
 * 抽象工厂模式 
 * ------------- 
 * @author      zhaoxuejie <zxj198468@gmail.com> 
 * @package     design pattern  
 * @version     v1.0 2011-12-14 
 */ 
 
//---------------------------------------------------------------------------
// 抽象工厂(AbstractFactory)角色:它声明一个创建抽象产品对象的接口。
// 通常以接口或抽象类实现,所有的具体工厂类必须实现这个接口或继承这个类。
//---------------------------------------------------------------------------
// 具体工厂(ConcreteFactory)角色:实现创建产品对象的操作。
// 客户端直接调用这个角色创建产品的实例。这个角色包含有选择合适的产品对象的逻辑。通常使用具体类实现。
//---------------------------------------------------------------------------
// 抽象产品(Abstract Product)角色:声明一类产品的接口。它是工厂方法模式所创建的对象的父类,或它们共同拥有的接口。
//---------------------------------------------------------------------------
// 具体产品(Concrete Product)角色:实现抽象产品角色所定义的接口,定义一个将被相应的具体工厂创建的产品对象。
// 其内部包含了应用程序的业务逻辑。
//---------------------------------------------------------------------------

///抽象工厂
interface AnimalFactory{
	public function createCat();
	public function createDog();
}

//黑色动物具体工厂
class BlackAnimalFactory implements AnimalFactory{
	function createCat(){
		return new BlackCat();
	}
	function createDog(){
		return new BlackDog();
	}

}
//白色动物具体工厂
class WhiteAnimalFactory implements AnimalFactory{
	function createCat(){
		return new WhiteCat();
	}
	function createDog(){
		return new WhiteDog();
	}
}

//抽象产品
interface Cat{
	function Voice();
}
interface Dog{
	function Voice();
}


//具体产品 
class BlackCat implements Cat {  
      
    function Voice(){  
        echo &#39;黑猫喵喵……&#39;;  
    }  
}  
  
class WhiteCat implements Cat {  
      
    function Voice(){  
        echo &#39;白猫喵喵……&#39;;  
    }  
}  
  
class BlackDog implements Dog {  
      
    function Voice(){  
        echo &#39;黑狗汪汪……&#39;;        
    }  
}  
  
class WhiteDog implements Dog {  
      
    function Voice(){  
        echo &#39;白狗汪汪……&#39;;        
    }  
}  


//客户端


class CLient{
	public static function main(){
		self::run(new BlackAnimalFactory());
		self::run(new WhiteAnimalFactory());
	}
	public static function run(AnimalFactory $AnimalFactory){
	
		$cat=$AnimalFactory->createCat();
		$cat->Voice();
		$dog=$AnimalFactory->createDog();
		$dog->Voice();
	}
}
CLient::main();


更多php 开发模式之工厂模式相关文章请关注PHP中文网!

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