分类
php

php 常用设计模式

单例模式:

<?php

# 单例模式

class RedisServer{

    static protected $ins = null;

    public static function getIns(){
        if(self::$ins === null){
            self::$ins = new self();
        }
        return self::$ins;
    }

    // final禁止覆盖构造方法,并且不允许通过new产生实例
    final protected function __construct()
    {

    }

    // 外部不允许使用 clone方法,并且不允许对其覆盖
    final protected function __clone()
    {

    }
}

$ins1 = RedisServer::getIns();
$ins2 = RedisServer::getIns();
if($ins1 === $ins2){
    echo "是一个对象";
}else{
    echo "不是一个对象";
}

工厂模式:

<?php

# 工厂模式

// 定义接口
interface DB
{
    public function toConnect();
}

// 定义服务类
class MysqlServer implements DB
{
    public function toConnect()
    {
        echo "已经连接mysql\n";
    }
}

class MongoDBServer implements DB
{
    public function toConnect()
    {
        echo "已经连接mongoDB\n";
    }
}


/**数据库服务工厂
 * Class DBServerFactory
 */
class DBServerFactory{
    protected static $serverArray = [];

    public static function getServer($serverName){
        if($serverName == 'mysql'){
            return new MysqlServer();
        }else if($serverName == 'mongodb'){
            return new MongoDBServer();
        }
    }
}

$dbServer = DBServerFactory::getServer('mysql');
$dbServer->toConnect();
$dbServer = DBServerFactory::getServer('mongodb');
$dbServer->toConnect();

观察者模式

可以实现系统接口

<?php

# 观察者模式,观察用户信息的改变

class User implements SplSubject
{
    // 观察者组
    protected $observers = null;

    // 名称
    public $name;
    public $age;


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

    // 变更姓名
    public function updateName($name)
    {
        $this->name = $name;
        $this->notify();
    }

    // 变更年龄
    public function updateAge($age)
    {
        $this->age = $age;
        $this->notify();
    }


    // 添加监听对象
    public function attach(SplObserver $observer)
    {
        $this->observers->attach($observer);
    }

    // 删除监听对象
    public function detach(SplObserver $observer)
    {
        $this->observers->detach($observer);
    }

    // 推送
    public function notify()
    {
        $this->observers->rewind();
        while($this->observers->valid()){
            $observer = $this->observers->current();
            $observer->update($this);
            $this->observers->next();
        }
    }
}


class TakeName implements SplObserver{
    public function update(SplSubject $subject){
        echo "用户的当前名称为{$subject->name}<br/>";
    }
}

class TakeAge implements SplObserver{
    public function update(SplSubject $subject){
        echo "用户的当前年龄为{$subject->age}<br/>";
    }
}

$user = new User('张三');
$user->attach(new TakeName());
$user->attach(new TakeAge());

$user->updateAge(123);
$user->updateName('王五');

发表评论

邮箱地址不会被公开。 必填项已用*标注