Detailed explanation of strategy pattern of PHP design patterns

韦小宝
Release: 2023-03-17 13:44:02
Original
1645 people have browsed it

Strategy Pattern encapsulates a specific set of behaviors and algorithms into classes to adapt to certain specific contexts. This pattern is Strategy Pattern, Strategy Pattern is used for free switching and expansion of algorithms. It is one of the more widely used design patterns.

Detailed explanation of strategy pattern of PHP design patterns

<?php
/*
 *策略模式
 */
interface FlyBehavior
{
    public function fly();
}

class FlyWithWings implements FlyBehavior
{
    public function fly()
    {
        echo "鸭子用翅膀飞行 \n";
    }
}

class FlyWithNo implements FlyBehavior
{
    public function fly()
    {
        echo "鸭子不用翅膀飞行 \n";
    }
}

class Duck
{
    private $_flyBehavior;

    public function performFly()
    {
        $this->_flyBehavior->fly();
    }

    public function setFlyBehavior(FlyBehavior $behavior) //被外部调用设置策略的
    {
        $this->_flyBehavior = $behavior;
    }
}

class RubberDuck extends Duck
{
}

// Test Case
$duck = new RubberDuck();

/*  想让鸭子用翅膀飞行 */
$duck->setFlyBehavior(new FlyWithWings());
$duck->performFly();

/*  想让鸭子不用翅膀飞行 */
$duck->setFlyBehavior(new FlyWithNo());
$duck->performFly();
Copy after login

The strategy pattern is used for free switching and expansion of algorithms. It is one of the most widely used design patterns. The strategy mode corresponds to an algorithm family that solves a certain problem, allowing the user to select an algorithm from the algorithm family to solve a certain problem, and at the same time, the algorithm can be easily replaced or a new algorithm added. As long as it involves algorithm encapsulation, reuse and switching, you can consider using the strategy pattern

Related recommendations:

Detailed explanation of PHP strategy pattern definition and usage examples

code sharing of PHP strategy pattern

StarCraft php strategy mode

The above is the detailed content of Detailed explanation of strategy pattern of PHP design patterns. For more information, please follow other related articles on the PHP Chinese website!

source:php.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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template