search
HomeBackend DevelopmentPHP TutorialLet's talk about the strategy pattern in PHP

Let's talk about the strategy pattern in PHP

Jul 09, 2021 pm 07:34 PM
phpstrategy patternDesign Patterns

In the previous article "In-depth analysis of the command mode in PHP" we introduced the command mode in PHP. This article will take you to understand the strategy mode in PHP.

Let's talk about the strategy pattern in PHP

Strategy pattern, also known as policy pattern, is a behavioral design pattern.

Gof class diagram and explanation

GoF definition: Define a series of algorithms, encapsulate them one by one, and make them interchangeable. This pattern allows the algorithm to change independently of the client using it.

GoF class diagram

Lets talk about the strategy pattern in PHP

##Code implementation

interface Strategy{
    function AlgorithmInterface();
}

class ConcreteStrategyA implements Strategy{
    function AlgorithmInterface(){
        echo "算法A";
    }
}

class ConcreteStrategyB implements Strategy{
    function AlgorithmInterface(){
        echo "算法B";
    }
}

class ConcreteStrategyC implements Strategy{
    function AlgorithmInterface(){
        echo "算法C";
    }
}

Define algorithm abstraction and implementation.

class Context{
    private $strategy;
    function __construct(Strategy $s){
        $this->strategy = $s;
    }
    function ContextInterface(){
        
        $this->strategy->AlgorithmInterface();
    }
}

Define the execution environment context.

$strategyA = new ConcreteStrategyA();
$context = new Context($strategyA);
$context->ContextInterface();

$strategyB = new ConcreteStrategyB();
$context = new Context($strategyB);
$context->ContextInterface();

$strategyC = new ConcreteStrategyC();
$context = new Context($strategyC);
$context->ContextInterface();

Finally, the appropriate algorithm is called on the client side as needed.

    Isn’t it a very simple design pattern. Have you noticed that this model is very similar to the
  • Simple Factory we first talked about?
  • So what are their differences?
  • The factory-related mode is a creation mode. As the name suggests, this mode is used to create objects and returns new objects. It is up to the client to decide which method of the object to call.
  • The strategy mode attribute behavioral mode encapsulates the function method to be called through the execution context. The client only needs to call the method of the execution context. Okay
  • Here, we will find that the client is required to instantiate specific algorithm classes, which seems not as easy to use as
  • Simple factory. In this case, why not try to combine the factory How about implementing a pattern together with the strategy pattern?
  • I leave this implementation to everyone as a thinking question. Tip: Turn the __construct of the Context class into a simple factory method

Since it is so similar to a simple factory, Then we also follow the simple factory method: we are a mobile phone manufacturer (Client) and want to find a factory (ConcreteStrategy) to make a batch of mobile phones. We place an order with this factory to manufacture mobile phones through the channel provider (Context). The channel provider directly Contact the foundry (Strategy) and ship the completed mobile phone directly to me (ContextInterface()). Similarly, I don’t need to care about their specific implementation. I only need to supervise the channel vendors who contact us. Isn’t it very worry-free!

Full code: https://github.com/zhangyue0503/designpatterns-php/blob/master/10.strategy/source/strategy.php

Example

It still has the SMS function. For specific requirements, please refer to the explanation in the

Simple Factory mode, but this time we use the strategy mode to implement it!

SMS sending class diagram

Lets talk about the strategy pattern in PHP

Full source code: https://github.com/zhangyue0503/designpatterns-php /blob/master/10.strategy/source/strategy-message.php

<?php

interface Message
{
    public function send();
}

class BaiduYunMessage implements Message
{
    function send()
    {
        echo &#39;百度云发送信息!&#39;;
    }
}

class AliYunMessage implements Message
{
    public function send()
    {
        echo &#39;阿里云发送信息!&#39;;
    }
}

class JiguangMessage implements Message
{
    public function send()
    {
        echo &#39;极光发送信息!&#39;;
    }
}

class MessageContext
{
    private $message;
    public function __construct(Message $msg)
    {
        $this->message = $msg;
    }
    public function SendMessage()
    {
        $this->message->send();
    }
}

$bdMsg = new BaiduYunMessage();
$msgCtx = new MessageContext($bdMsg);
$msgCtx->SendMessage();

$alMsg = new AliYunMessage();
$msgCtx = new MessageContext($alMsg);
$msgCtx->SendMessage();

$jgMsg = new JiguangMessage();
$msgCtx = new MessageContext($jgMsg);
$msgCtx->SendMessage();

Explanation

    Pay attention to compare the following class diagrams, basically and
  • Simple FactoryThere is no difference in the pattern
  • The strategy pattern defines algorithms. Conceptually, these algorithms complete the same work, but the implementation is different, but things are dead, people It is alive. How you want to use it depends on everyone's interest.
  • Strategy mode can optimize unit testing, because each algorithm has its own class, so it can be tested individually through its own interface
Original address: https://juejin.cn/post/6844903955860996110

Author: Hardcore Project Manager

Recommended study: "

PHP video tutorial

The above is the detailed content of Let's talk about the strategy 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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

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 Mac version

Dreamweaver Mac version

Visual web development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools