当前位置: 首页 > Linux

PHP设计模式-Singleton单例(单元素)模式

时间:2023-04-06 03:27:51 Linux

整理了一些AaronSaray写的PHP设计模式的demo和自己的理解。看完如果发现我的理解有误,请立即指出,感谢拍赞,求鞭笞/***Singleton单例(单元素)模式实现*------------------------------------***根据描述****通过提供对自身共享实例对的访问,单个元素(单例)设计模式用于限制特定对象只能创建一次。*这个对象最多可以存储自己的5个实例,如果有第6个请求,你必须等待。*或者只提供对先前创建的5个实例之一的引用这种架构类型在排队请求时特别有用**=====================================***应用场景****最常用于数据库连接对象,数据库访问对象可以负责创建与数据库的实例化连接。*接下来,每当调用此对象的特定方法时,该对象将使用已成功创建的连接。*从而减少服务器开销*----------------------------------**@version${Id}$*@authorShaoweiPu*/*@CreateTime2017-02-08T11:20:19+0800*@return[type][description]*/privatefunction__clone(){}/***[__constructcannotbenew]*@authorShaoweiPu*@CreateTime2017-02-08T11:18:09+0800*/privatefunction__construct(){try{$this->pdo=new\PDO("mysql:dbname=数据库名;host=127.0.0.1,root,123456");$this->pdo->exec('SETNAMESutf8');//设置通信编码$this->pdo->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);}catch(PDOException$e){die('error:'.$e->getMessage());}}/***[getinstancesingletonstart]*@authorShaoweiPu*@CreateTime2017-02-08T11:21:31+0800*@return[type][description]*/publicstaticfunctiongetInstance(){//检查它不是这个类的实例if(!self::$_instanceinstanceofself){self::$_instance=newself;}返回自我::$_实例;}/***[选择简单查询操作]*@authorShaoweiPu*@CreateTime2017-02-08T12:11:06+0800*@param[type]$dbname[description]*@param[type]$filed[description]*@param[type]$where[description]*@return[type][描述]*/publicfunctionselect($dbname,$filed,$where){$stmt=self::$_pdo->prepare("SELECT{$filed}FROM{$dbname}{$where}");$stmt->执行();返回$stmt->fetchAll(PDO::FETCH_ASSOC);}}单例::getInstance();