php中单件模式(singleton pattern)完整实例
来源:互联网 发布:ghost后数据恢复 编辑:程序博客网 时间:2024/05/16 04:41
单件模式属于构造型模式,特别适合于向log记录等等应用,特点是只存在一个该类的实例. 方法:在类中定义一个一个静态变量来引用该类的实例以及一个静态方法,返回实例. 具体请看代码:实例比较简单,是为了让大家对单件模式有个理解,其他模式相关代码以后放出.
<?php/* * 1.Singleton Pattern for the log of application * 2.建议将类文件名写成class.log.php * 以便__autoload()自动载入该类 * 3.Author:NoAngels * 4.E-mail:flare_1023@163.com QQ:82535599 */final class log{#构造函数,日志文件不存在就创建否则就打开文件以供后续使用private function __construct(){if(!$this->__fp = @fopen('application.log', 'ab+')){$this->__errMsg = '创建或读取日志文件失败';$this->__errorHandler();}}#析构函数,释放资源function __destruct(){#站位先}#静态函数,配合静态变量使用,实现singleton设计模式static function getInstance(){if(self::__instance == NULL){self::__instance = new log;}return self::__instance;}#类内部错误处理机制private function __errorHandler(){die($this->__errMsg);}#将指定内容写入到日志文件中public function inLog($temp){if(@fwrite($this->__fp, time()."|||".$temp."/r/n") === FALSE){$this->__errMsg = '写入到日志文件失败';$this->__errorHandler();}return;}#将日志内容输出,参数默认为1,即默认用类内部方法打印日志,否则可自定义显示方式.两种情况下都返回数组public function outLog($default = 1){$outArray = array();while(!feof($this->__fp)){$line = fgets($this->__fp);if(strlen($line) != 0){$tmp = explode("|||", $line, 2);$outArray[] = $tmp;}}if($default == 1){$this->__printLog($outArray);}return $outArray;}#默认日志输出方式private function __printLog($arr){foreach($arr as $temp){echo '记录时间:'.date('Y-m-d H:m:s' , $temp[0]).'<br/>原因:'.$temp[1].'<br/>';}}#私有变量,初始化每个变量static private __instance = NULL;private __fp = NULL;private __errMsg = '';}?><?php#测试方法try{if(!@mysqli_connect('localhost', 'root', '10d237776')){throw new Exception('mysql connect failed!');}}catch(Exception $e){print 'y';log::getInstance()->inLog($e->getMessage());}?>
- php中单件模式(singleton pattern)完整实例
- Singleton Session Pattern (单实例会话模式)
- PHP单例模式(Singleton Pattern)
- Net设计模式实例之单例模式( Singleton Pattern)
- Net设计模式实例之单例模式( Singleton Pattern)
- Design Pattern: Singleton 模式
- Design Pattern: Singleton 模式
- 单件模式(Singleton Pattern)
- 设计模式学习 (Singleton Pattern)
- 单例模式(Singleton Pattern)
- 单件模式(Singleton Pattern)
- Singleton Pattern (单例模式)
- 单例模式( Singleton Pattern)
- 单例模式【SINGLETON PATTERN 】
- 单例模式(Singleton Pattern)
- 单件模式(Singleton Pattern)
- 单例模式【Singleton Pattern】:
- 单例模式(singleton pattern)
- Asp.Net DataTable 简单分页(新)
- template关键字
- IE下,纯js掉用系统activex实现文件下载。
- IE下,纯js掉用系统activex实现文件下载。
- Vim Shortcut in a fast guide
- php中单件模式(singleton pattern)完整实例
- 服务器响应的生成:HTTP响应报头——HttpServletResponse接口的应用
- Vim Search
- 服务器响应的生成:HTTP状态代码——HttpServletResponse接口应用
- 谷歌公交搜索之我见
- 自动化测试框架:上次TestAge交流的时候的录像
- TCP(socket vc) client
- AT&T 的 3D 浏览器 - Pogo
- 摘:一张废手机卡的作用