策略模式:就是把算法和对象分离开,使算法可以独立改变,

而调用它的客户(环境类)不用做相应的改变的开发模式。

<?php

/*

//策略模式的组成:

1.环境类,一个私有成员,一个私有成员赋值方法,

该方法有一个形式参数,参数的类型是策略的实体类,

函数体用该参数来确定具体调用那个具体实体策略类的方法,

这样不同实体类调用不同的算法,

就实现了对象和算法的分离。

2.一个抽象的策略类,在抽象类中实现算法的封装的声明。

3.多个策略实体类(具体算法类),继承抽象的策略类,并重写算法的声明。

*/

interface Strategy

{

public function treal();

}

class Ari implements Strategy

{

public function treal()

{

echo 'ari for treal!';

}

}

class Train implements Strategy

{

public function treal()

{

echo 'train for treal!';

}

}

class Bicycle implements Strategy

{

public function treal()

{

echo 'bicycle for treal!';

}

}

//环境类

class person

{

private $treals=null;

public function __construct(Strategy $strategy)

{

$this->treals=$strategy;

}

public function setTreal(Strategy $strategy)

{

if($strategy)

{

$this->treals=$strategy;

}

}

public function Display()

{

$this->treals->treal();

}

}


$person=new person(new Ari());

$person->Display();

    

    $person=new person(new Train());

$person->Display();

    

    $person=new person(new Bicycle());

$person->Display();

?>