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

A brief discussion on the factory method pattern in PHP

青灯夜游
青灯夜游forward
2021-06-17 18:21:122528browse

This article takes you through the factory method 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 factory method pattern in PHP

As mentioned last time, simple factory does not belong to the twenty-three design patterns of GoF. This time it comes to the real guy, the famous factory Method pattern comes to report!

Related recommendations: " A brief talk about the simple factory pattern in PHP"

GoF class diagram explanation

Compared with the simple factory, the core point of the factory method pattern is to defer implementation to subclasses. How to understand it? We can use the simple factory from last time as the parent class, and then have a bunch of subclasses inherit it. The createProduct() method also becomes an abstract method in the parent class. Then all subclasses implement this method. There is no need to use switch to judge. The subclass can directly return an instantiated object.

GoF definition: Define an interface for creating objects and let subclasses decide which class to instantiate. Factory Method defers instantiation of a class to its subclasses.

GoF class diagram:

A brief discussion on the factory method pattern in PHP

    ##The Product in the class diagram is product
  • Creator in the class diagram is the creator
  • The creator parent class has an abstract FactoryMethod() factory method
  • All creator subclasses need to implement this factory method and return the corresponding Specific products
  • The creator parent class can have an AnOperation() operation method, which directly returns the product. You can use FactoryMethod() to return, so that the outside only needs to call AnOperation() in a unified manner

Code implementation

The first is the product-related interface and implementation class, which is similar to that of a simple factory:

// 商品接口
interface Product{
    function show() : void;
}

// 商品实现类A
class ConcreteProductA implements Product{
    public function show() : void{
        echo "I'm A.\n";
    }
}

The next is the abstract and implementation class of the creator:

// 创建者抽象类
abstract class Creator{

    // 抽象工厂方法
    abstract protected function FactoryMethod() : Product;

    // 操作方法
    public function AnOperation() : Product{
        return $this->FactoryMethod();
    }
}

// 创建者实现类A
class ConcreteCreatorA extends Creator{
    // 实现操作方法
    protected function FactoryMethod() : Product{
        return new ConcreteProductA();
    }
}

This is fundamentally different from a simple factory. We have removed the disgusting switch and let each specific implementation class create product objects. That's right, single and closed. Each individual creator subclass is only coupled to one product in the factory method. I don't know if there are other products and other factories that have cooperated with customers in this subclass.

Let’s use the analogy of mobile phones again: I am a wholesaler (Client, business side) selling mobile phones. I need a batch of mobile phones (Product A), so I went to get Foxconn ( Factory Creator) to help me produce. I explained my needs to Foxconn, and Foxconn agreed to let my Hengyang factory (ConcreteCreatorA) handle it. There is no need to go to the main factory. Your small order is just a waste. Then after a while, I needed another model of mobile phone (Product B). Foxconn looked at it and asked Zhengzhou Foxconn (Concrete Creator B) to help me produce it. Anyway, no matter what, they always gave me the corresponding mobile phone. Moreover, the Zhengzhou factory does not know what the Hengyang factory has produced or whether it has cooperated with me. Only I and the main factory know all this.

Complete code: Factory method pattern

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

Example

Scenario: Just talk without practicing tricks, send and modify the last text message, we still use the last one Several SMS senders. After all, everyone is already familiar with it, but it may need to be replaced in the future. Shopping malls are like battlefields, and everyone's interests should come first. In this case, we can decouple it through the factory method pattern, and we can easily add and modify SMS providers.

SMS sending class diagram

A brief discussion on the factory method pattern in PHP

Code implementation

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


abstract class MessageFactory{
    abstract protected function factoryMethod();
    public function getMessage(){
        return $this->factoryMethod();
    }
}

class AliYunFactory extends MessageFactory{
    protected function factoryMethod(){
        return new AliYunMessage();
    }
}

class BaiduYunFactory extends MessageFactory{
    protected function factoryMethod(){
        return new BaiduYunMessage();
    }
}

class JiguangFactory extends MessageFactory{
    protected function factoryMethod(){
        return new JiguangMessage();
    }
}

// 当前业务需要使用百度云
$factory = new BaiduYunFactory();
$message = $factory->getMessage();
echo $message->send(&#39;您有新的短消息,请查收&#39;);

Complete Source code: SMS sending factory method

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

Explanation

    It is completely consistent with the class diagram. There is basically no need for any explanation. Pay attention to the characteristics of the factory method pattern, and the implementation is postponed to the subclass! !
  • You need to couple a Factory subclass when calling the business. This is indeed the case. If you want a unified outlet to call, please add a simple factory outside. This is a question to think about.
  • Don’t stick to the current form, you don’t need abstract classes , directly use an interface to define the factory method, abandon the getMessage() method, and directly call the public template method (factoryMethod) externally
Recommended learning: "

PHP Video Tutorial

The above is the detailed content of A brief discussion on the factory method 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