策略者模式

策略者模式:

  定义了算法组,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用的算法客户!

 

案例解析:

   游戏中的不同的角色可以使用不同的武器来进行打仗!

   国王 => 宝剑

    士兵 => 刀

 

  定义角色接口(InterRole.php)

<?php


interface InterRole
{
    public function fight(); //打架

}

定义角色基类(BaseRole.php)

<?php

class BasiRole
{
    protected $weaponBehavior; //兵器行为
    //设置武器
    public function setWeapon(WeaponBehavior $behavior){
        $this->weaponBehavior = $behavior;
    }
}

 定义国王角色(KingRole.php)

<?php
class KingRole extends BasiRole implements InterRole
{
    public function __construct(){

    }

    public function fight()
    {
        //设置武器
        $this->setWeapon(new SwordBehavior());
        //打架
        $this->weaponBehavior->useWeapon();
    }
}

定义士兵角色(SoldierRole.php)

<?php


class SoldierRole extends BasiRole implements InterRole
{

    public function fight()
    {
        //设置武器
        $this->setWeapon(new KnifeBehavior());
        //打架
        $this->weaponBehavior->useWeapon();
    }
}

定义武器行为接口(WeaponBehavior.php)

<?php


interface WeaponBehavior
{
    //使用武器
    public function useWeapon();
}

定义刀的实现体(KnifeBehaviro.php)

<?php


class KnifeBehavior implements WeaponBehavior
{

    public function useWeapon()
    {
        echo 'I am  knife';
    }
}

定义宝剑的实现体(SwordBehavior.php)

<?php


class SwordBehavior extends BasiRole implements WeaponBehavior
{

    public function useWeapon()
    {
        echo 'I am sword';
    }
}

定义启动入口程序(index.php)

<?php
function __autoload($class){
    if ($class) {
        $file = str_replace('\\', '/', $class);
        $file .= '.php';
        if (file_exists($file)) {
            include $file;
        }
    }
}
//实例化国王
$role = new KingRole();
$role->fight();

//实例化士兵
$role2 = new SoldierRole();
$role2->fight();

目录文件展示

 

 

执行命令

 

 总结:

   通过接口定义(角色接口)找到需要差异化实现的特性,通过继承(BaseRole)找到通用的特性,通过封装算法(武器行为类),让算法和使用者解耦,更加独立!

  多用组合,少用继承!

 

posted @ 2022-11-07 17:38  祥子zzz  阅读(37)  评论(0)    收藏  举报