设计模式二:门面模式

门面模式:

  又称外观模式,为子系统中的一组接口提供一个高层的统一接口。使得子系统接口更容易调用。

/**
 * Redis 链接类
 */
class RedisConnect{
    
    private function connection(){
        $redis = new Redis();
        $redis->connect('47.99.117.126',6379);
        $redis->auth('huawu@2016');
        return $redis;
    }

    public function conn(){
        return $this->connection();
    }
}

/**
 * Redis 操作类
 */
class RedisHandle{

    private $redis;

    public function __construct(){
        $redisCon = new RedisConnect();
        $this->redis = $redisCon->conn();
    }

    public function set($key,$value)
    {
        return $this->redis->set($key,$value);
    }

    public function get($key)
    {
        return $this->redis->get($key);
    }

    public function lpush($key,$value)
    {
        return $this->redis->lpush($key,$value);
    }

    public function llen($key)
    {
        return $this->redis->llen($key);
    }

    public function lrange($key,$start = 0,$length)
    {
        return $this->redis->lrange($key,$start,$length);
    }

}

/**
 * 门面类
 */
class Facade{
    public static function __callStatic($method, $args)
    {
        $instance = static::resolveFacadInstance(static::getFacadeClass());
        if(!$instance){
            throw new RuntimeException('获取类实例失败');
        }
        return $instance->$method(...$args);
    }

    private static function resolveFacadInstance($name){
        if(is_object($name))
            return $name;
        return (new $name);
    }
}

/**
 * 
 */
class RedisSelf extends Facade
{
   protected static function getFacadeClass()
   {
       return 'RedisHandle';
   }
}
print_r(RedisSelf::set('name','张三'));
print_r(RedisSelf::get('name'));

 

posted @ 2021-08-24 09:36  wish_yang  阅读(51)  评论(0编辑  收藏  举报