php按需加載方式來增長程序的靈活度

設計模式的命名啊什麼的,我基本上已經忘記得差很少了,我就把我如今表述的這個東西叫作按需加載吧。php

需求:

1.我但願有一個配置文件讀寫類,不須要修改本來這個配置文件讀寫類就能夠實現擴展;
2.這個擴展是好比我本來的配置是txt格式的,但如今個人配置類是php或者是xml等,也多是json
3.調用接口統一,無論什麼類型的配置文件,我調用一樣的 一個文件配置讀寫類就能夠了,防止後續的代碼很難維護。json

那麼:

1.首先,想到的是定義一個抽象類,不斷的繼承,經過繼承不用修改這個配置文件讀寫類;
2.可是,我就不能統一使用這個配置文件讀取類了,我調用的是我繼承後的這個類;設計模式

實現思想:

好了,廢話了那麼多,我這裏就來講一下個人實現思路,其實整個思路仍是挺簡單的;數組

/**
 * 定義配置文件讀寫類,全部的配置文件讀寫調用此類就能夠了,統一接口
 */
class Config {
    // 讀
    public function read($file,$type = 'txt') {
        $instance = $this->getInstance($type);
        $instance->read($file);
    }
    // 寫
    public function write($file,$type = 'txt') {
        $instance = $this->getInstance($type);
        $instance->read($file);
    }
    // 刪
    public function delete($file,$type = 'txt') {
        $instance = $this->getInstance($type);
        $instance->read($file);
    }
    // 獲取實際操做對象實例
    public function getInstance($type = 'txt') {
        $class_name = ucfirst($type).'Config'; // 根據文件格式實例化具體的操做類
        if(class_exists($class_name)) {
            $instance = new $class_name;
        } else {
            throw new Exception('未定義'.$class_name);
        }
        if(is_subclass_of($instance,'BaseConfig') !== 1) {
            throw new Exception('配置文件讀寫類必須繼承BaseConfig');
        }
        return $instance;
    }
}
// 定義一個基礎操做接口類,後續的文件讀寫必須繼承這個規範
abstract class BaseConfig {
    abstract protected function read($file) {}
    abstract protected function write($file) {}
    abstract protected function delete($file) {}
}
// Text配置文件讀寫類
TxtConfig extends BaseConfig {
    public function read($file) {}
    public function write($file) {}
    public function delete($file) {}
}
// 其餘配置文件讀寫類。。。

以上的代碼我沒測試過,我表達的僅僅是一個思想,固然,基於這種思想還能夠設計出更加靈活,能夠增長一個數組配置來定義不一樣的文件分別採用哪一個類來讀寫,時間關係,這個問題後續有時間再更新。測試

相關文章
相關標籤/搜索