3)它必须自行向整个系统提供这个实例。
<?php /** * MemcacheOperate.php * * 单例模式设计Memcache操作类 * * Copyright (c) 2015 http://blog.csdn.net/CleverCode * * modification history: * -------------------- * 2015/6/8, by CleverCode, Create * */ class MemcacheOperate extends Memcache{ // 实例 protected static $_instance = null; /** * Singleton instance(获取自己的实例) * * @return MemcacheOperate */ public static function getInstance(){ if (null === self::$_instance) { self::$_instance = new self(); $host = $_SERVER['MEMCACHE_HOST']; $port = $_SERVER['MEMCACHE_PORT']; self::$_instance->addServer($host, $port); } return self::$_instance; } }
<?php /** * RedisOperate.php * * 单例模式设计Redis操作类 * * Copyright (c) 2015 http://blog.csdn.net/CleverCode * * modification history: * -------------------- * 2015/6/8, by CleverCode, Create * */ class RedisOperate extends Redis{ // 实例 protected static $_instance = null; /** * Singleton instance(获取自己的实例) * * @return RedisOperate */ public static function getInstance(){ if (null === self::$_instance) { self::$_instance = new self(); $host = $_SERVER['REDIS_HOST']; $port = $_SERVER['REDIS_PORT']; self::$_instance->connect($host, $port); } return self::$_instance; } }
<?php /** * singletonPattern.php * * 单例模式 * * Copyright (c) 2015 http://blog.csdn.net/CleverCode * * modification history: * -------------------- * 2015/6/8, by CleverCode, Create * */ // 加载Memcache include_once ('MemcacheOperate.php'); // 加载Redis include_once ('RedisOperate.php'); /* * 客户端类 * 让客户端和业务逻辑尽可能的分离,降低客户端和业务逻辑算法的耦合, * 使业务逻辑的算法更具有可移植性 */ class Client{ /** * 初始化配置文件 * * @return null */ public static function initConfig(){ // Memcache 主机 $_SERVER['MEMCACHE_HOST'] = '192.168.6.201'; // Memcache 端口 $_SERVER['MEMCACHE_PORT'] = 11211; // Redis 主机 $_SERVER['REDIS_HOST'] = '192.168.6.201'; // Redis 端口 $_SERVER['REDIS_PORT'] = 6379; } /** * 主函数 * * @return null */ public function main(){ // 初始化配置 self::initConfig(); // Memcache key1 MemcacheOperate::getInstance()->set('key1', 'Memcache CleverCode1', 0, 100); echo MemcacheOperate::getInstance()->get('key1'); echo "\r\n---\r\n"; // Memcache key2 MemcacheOperate::getInstance()->set('key2', 'Memcache CleverCode2', 0, 100); echo MemcacheOperate::getInstance()->get('key2'); echo "\r\n---\r\n"; // Redis key3 RedisOperate::getInstance()->set('key3', 'Redis CleverCode3'); echo RedisOperate::getInstance()->get('key3'); echo "\r\n---\r\n"; // Redis key4 RedisOperate::getInstance()->set('key4', 'Redis CleverCode4'); echo RedisOperate::getInstance()->get('key4'); echo "\r\n---\r\n"; } } /** * 程序入口 */ function start(){ $client = new Client(); $client->main(); } start(); ?>