一天一个设计模式(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'));
观察者模式

本文来自博客园,作者:Bin_x,转载请注明原文链接:https://www.cnblogs.com/Bin-x/p/7390034.html

原文地址:https://www.cnblogs.com/Bin-x/p/7390034.html