[随笔][设计模式][观察者模式][PHP]

  • 对于观察者模式,从面向过程的角度看,观察者首先向主题进行注册,然后主题通知观察者做出相应的动作。
  • 从面向对象的角度观察,主题提供注册和通知的接口,观察者提供自身操作的接口。

io多路复用select总结

c语言回调函数

https://segmentfault.com/a/1190000008293902

  • 在c语言中,通过函数指针实现回调函数。
  • 函数指针的定义:
void (*p_func)(int, int, float) = NULL;
typedef void (*tp_func)(int, int, int, float);    //    tp_func是一种新的用户自定义类型。

  • 观察者模式的php例子
<?php
// 主题接口
interface Subject{
    public function register(Observer $observer);
    public function notify();
}
// 观察者接口
interface Observer{
    public function watch();
}
// 主题
class Action implements Subject{
     public $_observers=array();
     public function register(Observer $observer){
         $this->_observers[]=$observer;
     }

     public function notify(){
         foreach ($this->_observers as $observer) {
             $observer->watch();
         }

     }
 }

// 观察者
class Cat implements Observer{
     public function watch(){
         echo "Cat watches TV<hr/>";
     }
 } 
 class Dog implements Observer{
     public function watch(){
         echo "Dog watches TV<hr/>";
     }
 } 
 class People implements Observer{
     public function watch(){
         echo "People watches TV<hr/>";
     }
 }



// 应用实例
$action=new Action();
$action->register(new Cat());
$action->register(new People());
$action->register(new Dog());
$action->notify();

猜你喜欢

转载自www.cnblogs.com/person3/p/9342612.html