例:买车时,需要哪种颜色,需要按照哪种方式进行缴税,可以再增加几种缴税方式,增加多种颜色,为了让客户买到自己想要的车,策略模式就是为了解决此场景。
<?php
/**
* Stratedgy模式
*/
abstract class Tax
{
abstract public function setTax();
}
class EnTax extends Tax
{
public function setTax()
{
echo "English TAX Method";
}
}
class CNTax extends Tax
{
public function setTax()
{
echo "CHina TAX Method";
}
}
abstract class Color
{
abstract public function setColor();
}
class RedColor extends Color
{
public function setColor()
{
echo "Red Color";
}
}
class BlueColor extends Color
{
public function setColor()
{
echo "Blue Color";
}
}
class Car
{
private $tax;
private $color;
public function __construct(Tax $tax, Color $color)
{
$this->tax = $tax;
$this->color = $color;
}
public function setColor()
{
$this->color->setColor();
}
public function setTax()
{
$this->tax->setTax();
}
}
$cars[] = new Car(new EnTax(), new RedColor());
$cars[] = new Car(new CNTax(), new BlueColor());
foreach ($cars as $car) {
echo $car->setTax() . "<br>";
echo $car->setColor() . "<br>";
}