/** - * 工厂方法模式
- * -------------
- * @author zhangqian
- * @version v1.0
- */
- //缓存接口
- interface cache {
- public function init($conf);
- public function setVal($key , $val);
- public function getVal($key);
- public function delVal($key);
- public function autoIncreament($key);
- }
- //mem
- class mymemCache implements cache {
- //mymem连接
- public function init($conf)
- {
- echo '初始化mymem';
- }
- public function setVal($key , $val)
- {
- echo 'mem设置值';
- }
- public function getVal($key)
- {
- echo 'mem获取值';
- }
- public function delVal($key)
- {
- echo 'mem删除值';
- }
- public function autoIncreament($key)
- {
- echo 'mem自增';
- }
- }
- //redis
- class redisCache implements cache {
- //redis连接
- public function init($arr)
- {
- echo '初始化redis';
- }
- public function setVal($key , $val)
- {
- echo 'redis设置值';
- }
- public function getVal($key)
- {
- echo 'redis获取值';
- }
- public function delVal($key)
- {
- echo 'redis删除值';
- }
- public function autoIncreament($key)
- {
- echo 'redis自增';
- }
- }
- class cacheFactory
- {
- private static $obj;
- private static $type;
- private static $conf;
- private static $allowtype = array('mymem','redis');
- private static function getConfig()
- {
- //include_once('config.php');加载配置文件 获取缓存的类型 及缓存的配置参数
- global $_SC;
- self::$type = $_SC['cachetype'];//做空值的判断
- self::$conf = $_SC['cacheconf'];//做空值的判断
- }
- //外部调用创建缓存对象
- public static function CreateOperation(){
- self::getConfig();
- try
- {
- $error = '未知的缓存类型';
- if(in_array(self::$type , self::$allowtype))
- {
- $type = self::$type.'Cache';
- self::$obj = new $type;
- self::$obj->init(self::$conf);//连接
- }
- else
- throw new Exception($error);
- }
- catch (Exception $e) {
- echo 'Caught exception: ', $e->getMessage(), "\n";
- exit;
- }
- return self::$obj;
- }
- }
$_SC = array(); - $_SC['cachetype'] = 'redis';//mymem
- $_SC['cacheconf'] = array();
-
- $cache = cacheFactory::CreateOperation();
- $cache->setVal('a',1);
- echo '
'; - $a = $cache->getVal('a');
- echo '
'; - $cache->delVal('a');
- ?>
|