温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么实现php策略模式

发布时间:2021-10-19 09:18:10 来源:亿速云 阅读:119 作者:小新 栏目:web开发

小编给大家分享一下怎么实现php策略模式,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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

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

<?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();

?>

以上是“怎么实现php策略模式”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI