设计模式案例(个人笔记)

一、单例模式:

<?php

class Predis{

  public $redis = "";

  private static $_instance = null;

  public static function getInstance() {

    if(empty(self::$_instance)) {

      self::$_instance = new self();

    }

    return self::$_instance;

  }

 

  private function __construct() {

    $this->redis = new \Redis();

    $result = $this->redis->connect(config('redis.host'), config('redis.port'), config('redis.timeOut'));

    if($result === false) {

      throw new \Exception('redis connect error');

    }

  }

}

 

 

二、观察者模式

<?php

/**
 * 观察者模式
 */


interface Observer
{
    public function update();
}

abstract class EventGenerator
{
    private $observers = [];

    public function addObserver(Observer $observer)
    {
        $this->observers[] = $observer;
    }

    public function notify()
    {
        foreach ($this->observers as $observer)
        {
            $observer->update();
        }
    }
}

// 事物生成类
class Event extends EventGenerator
{
    public function trigger()
    {
        echo "Event<br />\n";
        $this->notify();
    }
}

//  观察者
class Observer1 implements Observer
{
    public function update()
    {
        echo "观察者1";
    }
}

class Observer2 implements Observer
{
    public function update()
    {
        echo "观察者2";
    }
}

$event = new Event;
$event->addObserver(new Observer1);
$event->addObserver(new Observer2);
$event->trigger();

 

posted @ 2018-09-10 09:07  郑楚周  阅读(327)  评论(0编辑  收藏  举报