illustrate
1. The factory pattern solves how to create instance objects without using new.
2. There are some ways to create targets other than new.
If you want to change the type of object created, you only need to change the factory, and all code using this factory will automatically change.
3. Usually used with interfaces, the application does not need to know the specific details of these instantiated classes.
It's easy to use as long as you know that the factory returns a class that supports a certain interface category.
Example
/** * Abstract a person's interface * Interface Person */ interface Person { public function showInfo(); } /** * A student class that inherits from the abstract human interface * Class Student */ class Student implements Person { public function showInfo() { echo "This is a studentn"; } } /** * A teacher class that inherits from the abstract human interface * Class Teacher */ class Teacher implements Person { public function showInfo() { echo "This is a teachern"; } } /** * Human Factory * Class PersonFactory */ class PersonFactory { public static function factory($person_type) { // Capitalize the first letter of the type passed in $class_name = ucfirst($person_type); if(class_exists($class_name)){ return new $class_name; }else{ throw new Exception("Class: $class_name does not exist",1); } } } // Need a student $student = PersonFactory::factory('student'); echo $student->showInfo(); // When you need a teacher $teacher = PersonFactory::factory('teacher'); echo $teacher->showInfo();
The above is an introduction to the PHP factory mode. I hope it will be helpful to everyone.