PHP策略模式之简单使用
2022-10-11 本文已影响0人
响呼雷
//文件名CelueService.php
//定义接口,衣服下有裤子、鞋子
interface Yifu
{
public function kuzi();
public function xiezi();
}
//淘宝裤子、鞋子
class Taobao implements Yifu
{
public function kuzi()
{
echo "toabao---kuzi";
}
public function xiezi()
{
echo "taobao---xiezi";
}
}
//京东裤子、鞋子
class Jingdong implements Yifu
{
public function kuzi()
{
echo "jingdong---kuzi";
}
public function xiezi()
{
echo "jingdong---xiezi";
}
}
class CelueService
{
private $obj;
//方式1:
public function __construct(Yifu $yifu)
{
$this->obj = $yifu;
}
// //方式2
// public function __construct($method)
// {
// $temp = new \ReflectionClass($method);
// $this->obj = $temp->newInstance();
// }
public function total_kuzi()
{
$this->obj->kuzi();
}
public function total_xiezi()
{
$this->obj->xiezi();
}
}
$obj = new CelueService(new Taobao());//需要京东就传new Jingdong()
$obj->total_xiezi();