Home > Backend Development > PHP Tutorial > PHP design pattern simple factory pattern

PHP design pattern simple factory pattern

韦小宝
Release: 2023-03-17 13:36:01
Original
1448 people have browsed it

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.

PHP design pattern simple factory 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();
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template