一天一个设计模式(17)——观察者模式

观察者模式

定义了对象之间的依赖,一旦其中一个对象的状态发生改变,依赖它的对象都会收到通知。

实例

<?php
class Job
{
    public $title;

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

class JobSeeker
{
    public $name;

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

    public function onJobPosted(Job $job)
    {
        echo 'Hi ' . $this->name . '!New job posted:' . $job->title.PHP_EOL;
    }
}

class JobPostings
{
    public $jobSeekers = [];

    private function notify(Job $job)
    {
        foreach ($this->jobSeekers as $jobSeeker) {
            $jobSeeker->onJobPosted($job);
        }
    }

    public function attach(JobSeeker $jobSeeker){
        $this->jobSeekers[]=$jobSeeker;
    }

    public function addJob(Job $job){
        $this->notify($job);
    }
}

$john=new JobSeeker('John');
$jack=new JobSeeker('Jack');

$posting=new JobPostings();
$posting->attach($john);
$posting->attach($jack);

$posting->addJob(new Job('teacher'));
观察者模式

 

posted @ 2017-08-18 15:45  Bin_x  阅读(223)  评论(0编辑  收藏  举报