2.22. 模板方法模式(Template Method)

未匹配的标注

定义

  1. 父类定义好相同的方法。 (一般都是抽象的 作为模板被子类继承)

  2. 子类来实现不同的方法

uml

模板方法模式(Template Method)

任务

laravelCache::rememberForever用法

$value = Cache::rememberForever('users', function() {
    return DB::table('users')->get();
});

代码是模仿rememberForever方法

代码实现


<?php

abstract class Cache
{
    abstract public function get($key);
    abstract public function set($key,$value);

    public function rememberForever($key,\Closure $func)
    {
        if( $this->get($key) == null)
        $this->set($key,$func());
        return $this->get($key);
    }
}

class Redis extends Cache {
    protected $data = [];
    public function get($key)
    {
        return $this->data[$key] ?? null;
    }
    public function set($key, $value)
    {
        $this->data[$key] = $value;
    }
}

class File extends Cache {
    public function get($key)
    { }
    public function set($key, $value)
    { }
}

$redis = new Redis();
echo $redis->rememberForever('user',function(){
    return 'this is user';
});

运行

this is user

本文章首发在 LearnKu.com 网站上。

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~