Define a factory class, Simple factory modeIt can return instances of different classes according to different parameters. The created instances usually have a common parent class. Because the method used to create instances in Simple Factory Pattern is a static method, Simple Factory Pattern is also called static factory method(Static Factory Method) pattern, which belongs to the class creation pattern.
/** *简单工厂模式 * */ abstract class userProperties { function getUsername() { } function getGender() { } function getJob() { } } class User extends userProperties { private $username; private $gender; private $job; public function __construct($username, $gender, $job) { $this->username = $username; $this->gender = $gender; $this->job = $job; } public function getUsername() { return $this->username; } public function getGender() { return $this->gender; } public function getJob() { return $this->job; } } class userFactory { public static function createUser($properties = []) { return new User($properties['username'], $properties['gender'], $properties['job']); } } $employers = [ ['username' => 'Jack', 'gender' => 'male', 'job' => 'coder'], ['username' => 'Marry', 'gender' => 'female', 'job' => 'designer'], ]; $user = userFactory::createUser($employers[0]); echo $user->getUsername();
The simple factory pattern provides a specialized factory class for creating objects, which separates the creation of objects from the use of objects. It is the simplest The factory pattern has been widely used in software development
Related recommendations:
php simple factory pattern example php design Pattern introductory tutorial
Comparison of PHP simple factory pattern, factory method pattern and abstract factory pattern
StarCraft PHP simple factory pattern
The above is the detailed content of PHP design pattern simple factory pattern. For more information, please follow other related articles on the PHP Chinese website!