search
HomeBackend DevelopmentPHP TutorialLet'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.

Let's talk about the abstract factory pattern in PHP

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:

Lets talk about the abstract factory pattern in PHP

  • 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

Lets talk about the abstract factory pattern in PHP

<?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;
    }
}

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

class AliYunPush implements Push{
    public function send(string $msg){
        // 调用接口,发送客户端推送
        // xxxxx
        return &#39;阿里云Android&iOS推送发送成功!推送内容:&#39; . $msg;
    }
}

class BaiduYunPush implements Push{
    public function send(string $msg){
        // 调用接口,发送客户端推送
        // xxxxx
        return &#39;百度Android&iOS云推送发送成功!推送内容:&#39; . $msg;
    }
}

class JiguangPush implements Push{
    public function send(string $msg){
        // 调用接口,发送客户端推送
        // xxxxx
        return &#39;极光推送发送成功!推送内容:&#39; . $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(&#39;您已经很久没有登录过系统了,记得回来哦!&#39;);
echo $push->send(&#39;您有新的红包已到帐,请查收!&#39;);

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment