策略模式将一族不同的算法(业务)封装到不同的类中。使Client类在不知道具体实现的情况下选择实例化其中一个算法。
首先策略模式需要有一个接口,然后不同的业务类(具有相同方法)均继承该接口,客户端方法可以使用接口类型参数。这样可以在不知道具体实现的情况下选择实例化其中一个算法。
/**
* 策略模式
* c面对接口编程,而非面对实现编程
*/
interface RideInterface
{
public function load();
}
class Bick implements RideInterface
{
public function load()
{
return '骑行很轻松';
}
}
class Car implements RideInterface
{
public function load()
{
return 'Very Cool!';
}
}
class Bus implements RideInterface
{
public function load()
{
return 'Safe and Cheap!';
}
}
class Client
{
private $vehicle;
public function setVehicleTool(RideInterface $vehicle)
{
$this->vehicle = $vehicle;
}
public function getVehicleTool()
{
return $this->vehicle->load();
}
}
$bus = new Bus();
$myVehicle = new Client();
$myVehicle->setVehicleTool($bus);
echo $myVehicle->getVehicleTool();