2.22. 模板方法模式(Template Method)
定义
父类定义好相同的方法。 (一般都是抽象的 作为模板被子类继承)
子类来实现不同的方法
uml

任务
laravel 的 Cache::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
                    
                    
                    
                
          
php设计模式学习
            
            
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: