我知道这可能会导致一场不必要的火焰战争,但我可以看到您可能需要多个数据库连接,所以我承认单例可能不是最好的解决方案......但是,我发现单例模式还有其他用途非常有用。
这是一个例子:我决定推出自己的 MVC 和模板引擎,因为我想要一些真正轻量级的东西。但是,我要显示的数据包含许多特殊的数学字符,例如 ≥ 和 μ 以及你有什么......数据在我的数据库中存储为实际的 UTF-8 字符,而不是预 HTML 编码,因为除了 HTML,我的应用程序还可以提供其他格式,例如 PDF 和 CSV。对 HTML 进行格式化的适当位置是在负责呈现该页面部分 (sn-p) 的模板(“视图”,如果您愿意的话)内。我想将它们转换为适当的 HTML 实体,但 PHP 的 get_html_translation_table() 函数不是很快。一次检索数据并将其存储为数组更有意义,以供所有人使用。这是我拼凑在一起测试速度的样本。据推测,无论您使用的其他方法(在获取实例之后)是否是静态的,这都会起作用。
class EncodeHTMLEntities {
private static $instance = null;//stores the instance of self
private $r = null;//array of chars elligalbe for replacement
private function __clone(){
}//disable cloning, no reason to clone
private function __construct()
{
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$this->r = array_diff($allEntities, $specialEntities);
}
public static function replace($string)
{
if(!(self::$instance instanceof self) ){
self::$instance = new self();
}
return strtr($string, self::$instance->r);
}
}
//test one million encodings of a string
$start = microtime(true);
for($x=0; $x<1000000; $x++){
$dump = EncodeHTMLEntities::replace("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)");
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds using singleton\n";
//now repeat the same without using singleton
$start = microtime(true);
for($x=0; $x<1000000; $x++){
$allEntities = get_html_translation_table(HTML_ENTITIES, ENT_NOQUOTES);
$specialEntities = get_html_translation_table(HTML_SPECIALCHARS, ENT_NOQUOTES);
$r = array_diff($allEntities, $specialEntities);
$dump = strtr("Reference method for diagnosis of CDAD, but clinical usefulness limited due to extended turnaround time (≥96 hrs)", $r);
}
$end = microtime(true);
echo "Run time: ".($end-$start)." seconds without using singleton";
基本上,我看到了这样的典型结果:
php test.php
运行时间:27.842966794968 秒使用单例
运行时间:237.78191494942 秒,不使用单例
因此,虽然我当然不是专家,但我没有看到一种更方便可靠的方法来减少对某种数据的缓慢调用的开销,同时使其超级简单(单行代码即可完成您的工作需要)。当然,我的示例只有一个有用的方法,因此并不比全局定义的函数好,但是一旦您有两种方法,您就会想要将它们组合在一起,对吗?我离基地很远吗?
另外,我更喜欢实际做某事的示例,因为有时当示例包含诸如“//在这里做一些有用的事情”之类的语句时,我很难想象这些语句,我在搜索教程时总是看到。
无论如何,我希望得到任何反馈或 cmets,说明为什么将单例用于此类事情是有害的(或过于复杂)。