当前位置: 代码迷 >> 综合 >> PHP策略模式实现demo
  详细解决方案

PHP策略模式实现demo

热度:77   发布时间:2023-10-29 14:47:14.0

策略模式是为了降低耦合,对相同的属性或方法进行封装,不同的地方通过调用实现各自的功能。策略模式是行为型模式,它定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。自己写了个demo,备忘一下

<?php
interface Human{
    public function shuxing();
}

class man implements Human{
    public function shuxing(){
        echo 'they are strong';
    }
}

class woman implements Human{
    
    public function shuxing()
    {
        echo 'they are soft';
    }
}

class somenone {
    private $human;
    
    public function shuxing()
    {
        $this->human->shuxing();
    }
    
    public function who(Human $human){
        $this->human = $human;
    }
}

class realate extends somenone{
    
}

$res = new realate();
$res->who(new man());
echo $res->shuxing();

  相关解决方案