对象池原理 php,Object Pool Design Pattern in PHP 对象池设计模式在PHP中应用举例

Object pooling can offer a significant performance boost; it is most effective in situations where the cost of initializing a class instance is high, the rate of instantiation of a class is high, and the number of instantiations in use at any one time is low.

对象池的应用可以提供显著的性能提升;当初始化某一个类的实例的成本很高的时候,又或者当某一个类的实例化的频率非常高的时候,又或者在任何一个时刻正在使用实例中的的数目却很低的时候,在以上情况下对象池的应用是非常有效的。

Object pools (otherwise known as resource pools) are used to manage the object caching. A client with access to a Object pool can avoid creating a new Objects by simply asking the pool for one that has already been instantiated instead. Generally the pool will be a growing pool, i.e. the pool itself will create new objects if the pool is empty, or we can have a pool, which restricts the number of objects created.

It is desirable to keep all Reusable objects that are not currently in use in the same object pool so that they can be managed by one coherent policy. To achieve this, the Reusable Pool class is designed to be a singleton class.

对象池(或称为资源池)被用于管理对象缓存。客户端通过简单地询问对象池中是否已经有了一个被实例化的对象从而避免重新创建一个新的对象。一般来说,池中对象将是会不断增长的,即池本身会创建新的对象,如果池是空的,或者我们可以有一个限制了被创建对象数量的对象池。

最好是保持所有当前未在同一个对象池使用的可复用的对象,以便它们可以由一连贯的策略来管理。为了实现这一目标,可重复使用的池类被设计成为一个单例类。

这个应该很简单理解,咱们可能都用到了,不管是数据库的连接还是memcache连接池,咱们一般都应用了这个模式,是建立在单例模式的基础之上的,因为在传统的GOF定义的23中设计模式中没有该模式,很多时候也认为是单例模式的一种衍生吧。

自己找一个简单的例子作为演示,遵守的不一定严格,重要的思想:

class DB

{

private static $instance;

private static $connArr = array();

static function getInstanse()

{

if (!isset(self::$instance))

{

self::$instance = new DB();

}

return self::$instance;

}

//实际项目中一般不是用PHP直连数据,会通过中间层来跟数据库建立持久链接

//避免每个PHP进程频繁跟数据库建立链接和释放链接

private function connect($hintId)

{

//需要根据 $hintId 定位一个库

list($host, $user, $pass, $dbname) = DBConfig::getHost($hintId);

//避免同一进程内多次重复连接同一数据库

$connkey = $host."_".$user."_".$pass."_".$dbname;

if (isset(self::$connArr[$connkey]))

{

return self::$connArr[$connkey];

}

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error)

{

die('Connect Error (' . $conn->connect_errno . ') ' . $conn->connect_error);

}

self::$connArr[$connkey] = $conn;

return self::$connArr[$connkey];

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值