PHP design mode: factory mode, php design mode Factory
Similar to the singleton mode, the Factory pattern mode is another creation mode.
Unlike the singleton mode, Singleton mode creates and manages a single object of a single type, while the factory mode creates multiple objects of multiple classes of different types.
Implementation of the factory Model
A simple factory model consists of three parts:
Next we will implement a simple factory model program step by step.
First, define an abstract base class:
// Define abstract base class abstract class People {// define abstract method abstract public function work ();}
Added the implementation of multiple base classes:
Class Coder extends People {public function work ("the programmer's job is to write code");} class Teacher extends People {public function work ("the Teacher's job is to teach and educate ");} class Cook extends People {public function work ("the Cook's job is to Cook delicious dishes ");}
Define a factory class to meet the needs of creating different objects:
// Factory Class Factory {// This method creates the required object static function createInstance ($ job) {$ job = ucfirst ($ job) based on the parameter ); return new $ job ;}}
Now, you can run the code to try:
$ P = Factory: createInstance ("Teacher"); $ p-> work (); // program output: the instructor's job is to teach and educate people $ m = Factory :: createInstance ("Coder"); $ m-> work (); // program output: the programmer's job is to write code $ w = Factory: createInstance ("Cook "); $ w-> work (); // program output: the cook's job is to cook delicious dishes.
Alternatively, you can modify the base class as follows:
// Define abstract base class abstract class People {// define abstract method abstract public function work (); /*###################################### * // define the factory method, and make it not inherit static final function createInstance ($ job) {$ job = ucfirst ($ job); return new $ job ;} /*###################################### */}
In this case, you can create an object as follows:
$ P = People: createInstance ("Teacher"); $ p-> work (); // program output: the instructor's job is to teach and educate People.
Advantages and Use Cases of the factory Model
Advantage: it reduces the Coupling Degree of the program and facilitates future maintenance and expansion.
Use Cases:
1. When the program is compiled, the exact object type cannot be determined when the object is generated. It is determined only when the program is running.
2. When you are not sure how many processing operations will be performed, the processing logic may be different for the received data, and new operations may be added in the future.