zoukankan      html  css  js  c++  java
  • 访问者模式

    原文链接: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()方法做了一个写日志的操作。

  • 相关阅读:
    消息队列中间件的技术选型分析
    数据库和缓存一致性的问题
    《RocketMQ 安装和使用》
    RocketMQ原理讲解系列文章
    阿里巴巴开源项目
    RocketMQ与Kafka对比(18项差异)
    对象初始化
    pytest_05_fixture之conftest.py
    pytest_04_测试用例setup和teardown
    Python与MogoDB交互
  • 原文地址:https://www.cnblogs.com/orlion/p/5350929.html
Copyright © 2011-2022 走看看