加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

访问者模式

发布时间:2020-12-14 04:46:36 所属栏目:百科 来源:网络整理
导读:原文链接:http://www.orlion.ga/752/ 解释: ? ? 访问者模式构造了包含某个算法的截然不同的对象,在父对象以标准方式使用这些对象时就会将该算法应用于父对象。需要的对象包含以标准方式应用于某个对象的算法时,最佳的做法是使用访问者模式。假如一个对象

原文链接:http://www.orlion.ga/752/

解释:

? ? 访问者模式构造了包含某个算法的截然不同的对象,在父对象以标准方式使用这些对象时就会将该算法应用于父对象。需要的对象包含以标准方式应用于某个对象的算法时,最佳的做法是使用访问者模式。假如一个对象中存在着一些与本对象不相干(或者关系较弱)的操作,为了避免这些操作污染这个对象,则可以使用访问者模式来把这些操作封装到访问者中去。

?

代码:

????首先是元素类,也就是被访问者CD:

namespace Vistor;

class CD {

public $name;

public function __construct($name) {
$this->name = $name;
}

public function buy() {
// do something ...
}

public function acceptVistor(CDVistor $cDVistor) {
$cDVistor->visitCD($this);
}
}

????然后是抽象访问者这里是一个接口:

namespace Vistor;

interface CDVistor {
public function visitCD(CD $cd);
}

????然后是访问者的实现:

namespace Vistor;

class CDVistorLogPurchase implements CDVistor {
public function visitCD(CD $cd) {
$logContent = $cd->name . ' was purchase';
echo $logContent;
// 写进日志文件
}
}

????最后是App.php:

require 'CDVistor.php';
require 'CDVistorLogPurchase.php';
require 'CD.php';

$cd = new VistorCD('test');
$cd->buy();
$cd->acceptVistor(new VistorCDVistorLogPurchase());

????从代码中我们可以看到,通过CD类的acceptVistor将访问者注入,在该方法的内部调用访问者的具体方法visitCD(),然后访问者的visitCD()方法做了一个写日志的操作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读