PHP设计模式—策略模式

举个小栗子,每天上学的时候,我可以坐公交, 可以开车,可能骑自行车,也可以步行。话不多说了, 直接上代码吧



namespace Design;


abstract class Strategy
{
    abstract function WayToSchool ();
}

class TrafficBus extends Strategy
{
    public function WayToSchool ()
    {
        echo '坐公交车去学校';
    }
}

class TrafficBike extends Strategy
{
    public function WayToSchool ()
    {
        echo '骑自行车去学校';
    }
}

class TrafficDrive extends Strategy
{
    public function WayToSchool ()
    {
        echo '开车去学校';
    }
}

class TrafficEleven extends Strategy
{
    public function WayToSchool ()
    {
        // TODO: Implement WayToSchool() method.
        echo '走路去学校';
    }
}

class GoToSchool
{
    private $strategy = null;

    public function __construct ( $way )
    {
        try {
            if ( !empty( $way ) ) {
                $strategy = new \ReflectionClass( $way );
                $this->strategy = $strategy->newInstance();
            } else {
                throw new \Exception( '请传入交通工具' );
            }
        } catch ( \Exception $e ) {
            print_r( $e );
        }
    }

    public function WayToSchool ()
    {
        return $this->strategy->WayToSchool();
    }
}


$strategy = new GoToSchool( '\Design\TrafficBike' );
$strategy->WayToSchool();

echo '<br>';
$strategy = new GoToSchool( '\Design\TrafficDrive' );
$strategy->WayToSchool();

echo '<br>';
$strategy = new GoToSchool( '\Design\TrafficEleven' );
$strategy->WayToSchool();


输出:

0

发表评论

电子邮件地址不会被公开。