Factory Pattern: The factory class determines which instance of the production class is created based on the parameters.
Factory class: A method class that is designed to create other objects. That is, on demand, the incoming parameters are selected to return the specific class
Actions: An object-created encapsulation that simplifies the creation of an object, a method of invoking a factory class to get the required class
Add:
1. Main roles : Abstract products (product), specific products (concrete product), Abstract factory role (Creator)
2. Advantages and Disadvantages
Advantage: The factory method model allows the system to introduce heart products without modifying the factory role
Disadvantage: Customers may have to create a creator subclass just to create a specific concrete product object
3. Applicability
When a class does not know the object it must create
When a class wants its subclasses to make the objects it creates
When a class delegates the responsibility of creating an object to one of several helper subclasses, and hopefully you will be the one that helps the subclass to be a proxy for this information localization
Copy Code code as follows:
<?php
Object
Class myobject{
Public Function __construct () {}
Public Function test () {
return ' test ';
}
}
Factory
Class myfactory{
public static function factory () {
return new MyObject ();
}
}
$myObject = Myfactory::factory ();
echo $myObject->test ();
?>
? <?php
Abstract classes define attributes 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;
}
}
............
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 ();
?>