Home  >  Article  >  Backend Development  >  A brief discussion on the simple factory pattern in PHP

A brief discussion on the simple factory pattern in PHP

青灯夜游
青灯夜游forward
2021-06-16 17:48:213788browse

This article takes you through the simple factory pattern in PHP design patterns. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

A brief discussion on the simple factory pattern in PHP

Let’s start with a simple factory. Whether it is an interview or being interviewed by others, when asked about design patterns, most people will mention the factory pattern. There is no doubt that several factory-related patterns are the most famous and widely used among design patterns. GoF design patterns are also creational patterns.

However, those who can explain the three modes of Simple Factory, Factory Pattern, and Abstract Factory Pattern can really impress the interviewer. . There is a premise here that you can really explain it clearly. Most people, including me, cannot explain it clearly before studying design patterns in depth. Whether it’s me going for an interview or interviewing someone else. When I interview others, I can only give a rough outline. When I went to the interview, I just gave a general outline. After experiencing many setbacks, I came up with the idea of ​​​​researching design patterns in depth, so this series of articles was produced. Starting from this simple factory, let's study design patterns in depth again.

Of course, PHP is used here.

Explanation

Simple factory, also known as static factory, does not belong to the GoF 23 design patterns. But it can be said that among all design patterns, it is probably the easiest for everyone to understand, and you may have already used this design pattern countless times in your code. Let’s start with the simplest code segment.

// Factory
class Factory
{
    public static function createProduct(string $type) : Product
    {
        $product = null;
        switch ($type) {
            case 'A':
                $product = new ProductA();
                break;
            case 'B':
                $product = new ProductB();
                break;
        }
        return $product;
    }
}

Yes, the core point is the simple switch code in the middle. We fixed the return value type as the implementation of the Product interface.

In this code, new features of PHP are used, Parameter type and Return value type

Product interface And product implementation

// Products
interface Product
{
    public function show();
}

class ProductA implements Product
{
    public function show()
    {
        echo 'Show ProductA';
    }
}

class ProductB implements Product
{
    public function show()
    {
        echo 'Show ProductB';
    }
}

Finally, the use of the client is very simple

// Client
$productA = Factory::createProduct('A');
$productB = Factory::createProduct('B');
$productA->show();
$productB->show();

As can be seen from the above code, in fact, here is a factory class based on the string we pass in or other definitions you make. identifier to return the corresponding product (Product object).

A more visual metaphor: I am a wholesaler (Client, business side) selling mobile phones. I need a batch of mobile phones (Product), so I go to Foxconn ( Factory) to help me produce. I placed an order ($type variable) and specified the model, and then Foxconn gave me the phone of the corresponding model, and then I continued my work. It was really pleasant to cooperate with Foxconn.

The more standardized way of writing here may be that all products will implement a unified interface, and then the client only knows how to call the interface methods uniformly. If it is not standardized, you can not use interfaces and return various objects, similar to the facade mode for unified facade management.

A brief discussion on the simple factory pattern in PHP

Source code address: Simple factory basic class diagram implementation

https://github.com/zhangyue0503/designpatterns-php/blob/master /01.simple-factory/source/simple-factory.php

Example

Scenario: SMS sending function module. Now we use the SMS services of three merchants, namely Alibaba Cloud, Diexin, and Jiguang. Different SMS senders may be used in different businesses. Using Simple Factory can easily fulfill this requirement.

Class diagram:

A brief discussion on the simple factory pattern in PHP

Code:

<?php

interface Message {
    public function send(string $msg);
}

class AliYunMessage implements Message{
    public function send(string $msg){
        // 调用接口,发送短信
        // xxxxx
        return &#39;阿里云短信(原阿里大鱼)发送成功!短信内容:&#39; . $msg;
    }
}

class BaiduYunMessage implements Message{
    public function send(string $msg){
        // 调用接口,发送短信
        // xxxxx
        return &#39;百度SMS短信发送成功!短信内容:&#39; . $msg;
    }
}

class JiguangMessage implements Message{
    public function send(string $msg){
        // 调用接口,发送短信
        // xxxxx
        return &#39;极光短信发送成功!短信内容:&#39; . $msg;
    }
}

Class MessageFactory {
    public static function createFactory($type){
        switch($type){
            case &#39;Ali&#39;:
                return new AliYunMessage();
            case &#39;BD&#39;:
                return new BaiduYunMessage();
            case &#39;JG&#39;:
                return new JiguangMessage();
            default:
                return null;
        }
    }
}

// 当前业务需要使用极光
$message = MessageFactory::createMessage(&#39;Ali&#39;);
echo $message->send(&#39;您有新的短消息,请查收&#39;);

Source code address : Simple factory instance-SMS sending factory

https://github.com/zhangyue0503/designpatterns-php/blob/master/01.simple-factory/source/simple-factory-message.php

illustrate

  • Must use static when creatingMessage? Not necessarily, it depends on your business situation. All statics that need to be resident, and those that are instantiated on demand can be new and then normal -> Do you need to implement the interface to call the
  • three message subclasses? Not necessarily. PHP itself is a weakly typed language and does not need to be enforced. However, the use of interfaces is more in line with object-oriented specifications (please refer to Polymorphism). The simple factory itself is actually a kind of polymorphism. Expression and Application
  • When you need to add a channel for sending messages, add a new class to inherit the Message interface, implement the send() method, and modify the switch in the createFactory() method in MessageFactory()
  • Thinking What object-oriented principle does the above modification violate? (Tip: Open XX)
  • The return value type is not used in the instance? This is also a new syntax. It does not need to be written for compatibility with older versions. However, if the company's technology stack has been upgraded to 7 or above, it is recommended that the code of this design pattern architecture class be written according to the new features explained above. , that is, with the parameter type and return value type, it is more consistent with the specification and easier to understand.
  • What should I do if $type is passed incorrectly and returns NULL in the example? Dear, please handle this problem well when actually writing code. Returning a default or upper-level capture are good solutions. Of course, it is best for the client to make a judgment in advance. If there is no problem, go to the factory.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of A brief discussion on the simple factory pattern in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete