The Factory mode (Factory pattern), like the singleton mode, is another type of creation pattern.
Unlike singleton mode, Singleton mode creates and manages a single object of a single type, and Factory mode is used to create multiple objects of many different types of classes.
Implementation of the factory model
The simple factory model consists of three parts:
- Abstract base class: Some methods of defining abstractions in a class to be implemented in subclasses;
- Inherits from the subclass of the abstract base class: Implements the abstract method in the base class;
- Factory class: Used to instantiate an object.
Here is a simple factory-mode program that is implemented in one step.
First, you define an abstract base class:
// defining abstract base classes Abstract class people{ // definition abstract public function Work ();}
To increase the implementation of multiple base classes:
class extends people{ publicfunction work ("The programmer's job is to write code");} class extends people{ publicfunction work ("The teacher's job is to educate and educate");} class extends people{ publicfunction work ("The chef's job is to make delicious dishes");}
Define the factory class to implement the requirements for creating different objects:
// Factory class Class factory{ // This method creates the desired object based on the parameter staticfunction CreateInstance ( $job ) { $jobucfirst($job); return New $job ; }}
Now, you can run the code and try it:
$p = factory::createinstance ("Teacher"); $pwork(); // program output: The teacher's job is educating $m = factory::createinstance ("coder"); $mwork(); // program output: The programmer's job is to write code $w = factory::createinstance ("Cook"); $wwork(); // Program output: Chef's job is to make delicious dishes
Alternatively, you can modify the base class like this:
//defining abstract base classesAbstract classpeople{//Defining abstract methods Abstract Public functionWork (); /*######################################*/ //define a factory method and make it non-inheritable Static Final functionCreateInstance ($job){ $job=Ucfirst($job); return New $job; } /*######################################*/}
At this point, you can create objects like this:
$p = people::createinstance ("Teacher"); $pwork(); // program output: The teacher's job is educating
Advantages of the factory model and usage scenarios
Advantages: Reduce the coupling degree of the program, convenient for future maintenance and expansion.
Usage scenarios:
1. When the program is written, it is not possible to determine the exact object type when the object is generated, and it is only determined when the program is running.
2. When unsure how many processing operations to take, such as the data received, the processing logic may be different, may add new operations in the future.
The Factory mode of PHP design mode