Let's talk about the abstract factory pattern in PHP
This article takes you through the abstract 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.
The highlight of the factory pattern series is here, yes, that is the rumored Abstract Factory Pattern. How did you feel when you first heard the name? Anyway, I feel that this thing should be very high-end, after all, it contains the word "abstract". It is said that these two words really have a high-level feeling in development. When used with the word abstract, it seems that everything is very powerful. However, Abstract Factory can indeed be said to be the big brother of the factory pattern.
Gof class diagram and explanation
In fact, as long as you understand the factory method pattern, it is easy to understand the abstract factory pattern. how to say? It's still the same delay to subclasses, and it's still the same return of the specified object. It's just that the abstract factory not only returns one object, but a bunch of them.
GoF definition: Provides an interface for creating a series of related or interdependent objects without specifying their specific classes.
GoF class diagram:
- On the left are two factories 1 and 2, both Inherit an abstract factory and implement the CreateProductA and CreateProductB methods
- Factory 1 produces ProductA1 and ProductB1
- Similarly, factory 2 produces ProductA2 and ProductB2
Code implementation
// 商品A抽象接口 interface AbstractProductA { public function show(): void; } // 商品A1实现 class ProductA1 implements AbstractProductA { public function show(): void { echo 'ProductA1 is Show!' . PHP_EOL; } } // 商品A2实现 class ProductA2 implements AbstractProductA { public function show(): void { echo 'ProductA2 is Show!' . PHP_EOL; } } // 商品B抽象接口 interface AbstractProductB { public function show(): void; } // 商品B1实现 class ProductB1 implements AbstractProductB { public function show(): void { echo 'ProductB1 is Show!' . PHP_EOL; } } // 商品B2实现 class ProductB2 implements AbstractProductB { public function show(): void { echo 'ProductB2 is Show!' . PHP_EOL; } }
Product implementation, there are a lot of things, this time there are actually four products, namely A1, A2, B1 and B2. Suppose there is something like this between them relationship, A1 and B1 are similar related products, B1 and B2 are similar related products
// 抽象工厂接口 interface AbstractFactory { // 创建商品A public function CreateProductA(): AbstractProductA; // 创建商品B public function CreateProductB(): AbstractProductB; } // 工厂1,实现商品A1和商品B1 class ConcreteFactory1 implements AbstractFactory { public function CreateProductA(): AbstractProductA { return new ProductA1(); } public function CreateProductB(): AbstractProductB { return new ProductB1(); } } // 工厂2,实现商品A2和商品B2 class ConcreteFactory2 implements AbstractFactory { public function CreateProductA(): AbstractProductA { return new ProductA2(); } public function CreateProductB(): AbstractProductB { return new ProductB2(); } }
And our factory is also factory 1 and factory 2, factory 1 produces two related products, A1 and B1 For the linked products, Factory 2 produces two products, A2 and B2. Okay, I know it's still a bit abstract here, and I may still not understand why this is the case. Let's continue to use mobile phone production as an example.
Our mobile phone brand has become popular, so we have handed over peripheral products such as mobile phone films and mobile phone cases to Abstract Factory to help me. As mentioned last time, I already have several different types of mobile phones, so I will continue as before. Hengyang Factory (Factory1) produces mobile phone model 1001 (ProductA1), and at the same time, the mobile phone film (ProductB1) and mobile phone case of model 1001 mobile phone (ProductB1). ProductC1) is also produced in Hengyang factory. The mobile phone model 1002 (ProductA2) is still in the Zhengzhou factory (Factory2), and the mobile phone film (ProductB2) and mobile phone film (ProductC2) of this model will be left to them. So, I just placed an order with the main factory. They asked different factories to produce a complete set of mobile phone products for me, and I could sell the set directly! !
Full code: Abstract Factory Pattern
https://github.com/zhangyue0503/designpatterns-php/blob/master/03.abstract-factory/source/ abstract-factory.php
Example
Are you still a little dizzy? In fact, to put it simply, it is really just returning different objects through different methods in a factory class. Let’s use the example of texting again to explain it!
Scenario: This time we have a business need to not only send text messages, but also send a push message at the same time. The purpose of text messages is to notify users that there are new activities to participate in, while push notifications not only notify users of new activities, but they can also click directly to receive red envelopes. Isn’t it exciting? Fortunately, the cloud service providers we chose before all have both SMS and push interfaces, so we will just use the abstract factory to implement it!
SMS sending class diagram
<?php interface Message { public function send(string $msg); } class AliYunMessage implements Message{ public function send(string $msg){ // 调用接口,发送短信 // xxxxx return '阿里云短信(原阿里大鱼)发送成功!短信内容:' . $msg; } } class BaiduYunMessage implements Message{ public function send(string $msg){ // 调用接口,发送短信 // xxxxx return '百度SMS短信发送成功!短信内容:' . $msg; } } class JiguangMessage implements Message{ public function send(string $msg){ // 调用接口,发送短信 // xxxxx return '极光短信发送成功!短信内容:' . $msg; } } interface Push { public function send(string $msg); } class AliYunPush implements Push{ public function send(string $msg){ // 调用接口,发送客户端推送 // xxxxx return '阿里云Android&iOS推送发送成功!推送内容:' . $msg; } } class BaiduYunPush implements Push{ public function send(string $msg){ // 调用接口,发送客户端推送 // xxxxx return '百度Android&iOS云推送发送成功!推送内容:' . $msg; } } class JiguangPush implements Push{ public function send(string $msg){ // 调用接口,发送客户端推送 // xxxxx return '极光推送发送成功!推送内容:' . $msg; } } interface MessageFactory{ public function createMessage(); public function createPush(); } class AliYunFactory implements MessageFactory{ public function createMessage(){ return new AliYunMessage(); } public function createPush(){ return new AliYunPush(); } } class BaiduYunFactory implements MessageFactory{ public function createMessage(){ return new BaiduYunMessage(); } public function createPush(){ return new BaiduYunPush(); } } class JiguangFactory implements MessageFactory{ public function createMessage(){ return new JiguangMessage(); } public function createPush(){ return new JiguangPush(); } } // 当前业务需要使用阿里云 $factory = new AliYunFactory(); // $factory = new BaiduYunFactory(); // $factory = new JiguangFactory(); $message = $factory->createMessage(); $push = $factory->createPush(); echo $message->send('您已经很久没有登录过系统了,记得回来哦!'); echo $push->send('您有新的红包已到帐,请查收!');
Complete source code: SMS sending factory method
https: //github.com/zhangyue0503/designpatterns-php/blob/master/03.abstract-factory/source/abstract-factory-message-push.php
Description
- Is it very clear?
- Yes, we have two products, one is Message and the other is Push, which are for sending messages and sending push messages respectively.
- The abstract factory only requires our interface implementers to implement two Method, returns the object of sending text messages and sending push messages
- Can you say that I only want to send text messages and not send push messages? Of course you can, just don’t call the createPush() method.
- What scenario is the abstract factory most suitable for? Obviously, the creation of a series of related objects
- The factory method pattern is the core of the abstract factory, which is equivalent to multiple factory methods being put into a large factory to produce a complete set of products (including peripherals) instead of a single Product
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of Let's talk about the abstract factory pattern in PHP. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
