A brief discussion on the simple factory pattern in PHP

青灯夜游
Release: 2023-04-10 08:26:01
forward
3691 people have browsed it

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 ofSimple Factory,Factory Pattern, andAbstract Factory Patterncan 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; } }
Copy after login

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 typeandReturn 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'; } }
Copy after login

Finally, the use of the client is very simple

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

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:

send('您有新的短消息,请查收');
Copy after login

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 toPolymorphism). 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!

source:juejin.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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!