zoukankan      html  css  js  c++  java
  • 一天一个设计模式(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

  • 相关阅读:
    2017.10.20
    2017.10.14
    2017.10.19
    2017.10.18
    2017.10.17
    软件工程个人作业02
    构建之法读后感03
    构建之法阅读笔记02
    二柱子问题(随机产生四则运算题目)
    课后作业2(构建之法阅读计划)
  • 原文地址:https://www.cnblogs.com/Bin-x/p/7390034.html
Copyright © 2011-2022 走看看