PHP – 策略模式

一、概述

  定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换,该模式使得算法可独立于使用它的客户而变化。

 

二、PHP 代码实现

<?php
declare(strict_types = 1);

interface UserType
{
    //显示广告
    function showAd();
    //展示类目
    function showCategory();

}

class MaleUserType implements UserType
{
    function showAd()
    {
        echo "this is 男性’s 广告条目数据";
    }

    function showCategory()
    {
        echo "this is 男性’s 商品类目数据";
    }
}


class FemaleUserType implements UserType
{
    function showAd()
    {
        echo "this is 女性’s 广告条目数据";
    }

    function showCategory()
    {
        echo "this is 女性’s 商品类目数据";
    }
}


class Home
{
    /**
     * @var UserType
     */
    protected $userType;

    /**
     * 首页展示数据
     * 使用策略模式
     * Index constructor.
     */
    function index()
    {
        echo "AD:";
        $this->userType->showAd();
        echo "Category:";
        $this->userType->showCategory();
    }

    /**
     * 策略模式
     * 根据传递的用户性别展示不同类别数据
     * @param UserType $userType
     */
    function setUserType(UserType $userType)
    {
        $this->userType = $userType;
    }

}

$obj = new Home();
if ($_GET['user_type'] == 'female'){
    $userType = new FemaleUserType();
} else {
    $userType = new MaleUserType();
}
$obj->setUserType($userType);
$obj->index();