PHP设计模式之——策略模式

来源:互联网 发布:今日财经数据 编辑:程序博客网 时间:2024/06/05 21:11

策略模式(Strategy Pattern)是对象的行为模式,是对一组算法的抽象封装,动态的选择算法使用。在我们的日常生活中,策略模式体现在方方面面:早上起床我去公司,可以坐公交,可以坐出租车,也可以步行,最终的目的都是到达公司,但是却使用了不同的资源。

策略模式的三个角色:

  1. 抽象策略角色
  2. 具体策略角色
  3. 环境角色(对抽象策略角色的引用)
策略模式的实现步骤:

  1. 定义抽象角色(类)或抽象方法(接口)(定义好各个实现的共同抽象方法)
  2. 定义具体策略类(实现父类的共同方法)
  3. 定义环境角色类(私有化声明抽象角色变量,重载构造方法,执行抽象方法)
策略模式的示例代码:

<?php/** * 策略模式   * */interface wayToSchool {    //定义抽象策略    public function way();}class wayWithCar implements wayToSchool {    //定义坐车去学校的具体策略    public function way() {        echo "goes to school by CAR!\n";    }}class wayWithBicycle implements wayToSchool {    //定义骑车去学校的具体策略    public function way() {        echo "goes to school by BICYCLE!\n";    }}class wayWithWalk implements wayToSchool {    //定义步行去学校的具体策略    public function way() {        echo "goes to school by WALK!\n";    }}class Student {    //定义环境角色类(学生)    private $_wayToSchool;    private $_name;    public function __construct($name) {        $this->_name = $name;    }    public function performance() {        echo $this->_name, " ";        $this->_wayToSchool->way();    }    public function setWayToSchool(wayToSchool $_way) {        $this->_wayToSchool = $_way;    }}$jerry = new Student("jerry");$tom = new Student("tom");$eggsy = new Student("eggsy");//实现不同策略$jerry->setWayToSchool(new wayWithCar);$jerry->performance();$tom->setWayToSchool(new wayWithBicycle);$tom->performance();$eggsy->setWayToSchool(new wayWithWalk);$eggsy->performance();


0 1
原创粉丝点击