PHP

The factory pattern based on php design pattern is introduced in detail


Factory pattern: The factory class determines, based on parameters, which instance of a production class to create Factory class: A method class dedicated to creating other objects. Assign as needed, pass in parameters for selection, and return the concrete class Purpose: Object creation encapsulates and simplifies object creation by calling a method of a factory class to get the required class Supplement: 1. Main roles: abstract product (Product), concrete product (Concrete Product), abstract factory role (Creator) 2. The advantages and disadvantages of Advantages: The factory method pattern allows the system to introduce core products without modifying the factory role Disadvantages: Customers may have to create a subclass of Creator just to create a specific Concrete Product object 3. The applicability When a class does not know which object it must create When a class wants its subclasses to specify the objects it creates When a class delegates the responsibility of creating an object to one of several helper subclasses and expects you to localize the information about which helper subclass is the proxy

<?php
// object
class MyObject{
    public function __construct(){}
    public function test(){
        return 'test';
    }
}
// The factory
class MyFactory{
    public static function factory(){
        return new MyObject();
    }
}

$myObject = MyFactory::factory();
echo $myObject->test();
?>
 
?<?php
// An abstract class   Define properties and abstract methods
abstract class Operation{
    protected $_NumberA = 0;
    protected $_NumberB = 0;
    protected $_Result= 0;

    public function __construct($A,$B){
        $this->_NumberA = $A;
        $this->_NumberB = $B;
    }

    public function setNumber($A,$B){
        $this->_NumberA = $A;
        $this->_NumberB = $B;
    }

    public function clearResult(){
        $this->_Result = 0;
    }

    abstract protected function getResult();
}

// Action class
class OperationAdd extends Operation{
    public function getResult(){
        $this->_Result = $this->_NumbserA + $this->_NumberB;
        return $this->_Result;
    }
}

class OperationSub extends Operation{
    public function getResult(){
        $this->_Result = $this->_NumberA - $this->_NumberB;
        return $this->_Result;
    }
}
 .....................

// The factory class
class OperationFactory{
    private static $obj;

    public static function CreationOperation($type,$A,$B){
        switch($type){
            case '+':
                self::$obj = new OperationAdd($A,$B);
                break;
            case '-':
                self::$obj = new OperationSub($A,$B);
                break;
             ...
        }
    }
}

// operation
$obj = OperationFactory:: CreationOperation('+',5,6);
echo $obj-> getResult();
?>