单例模式作为对象的创建模式,确保某一个类只有一个实例,而且自行实例化,并确保向系统提供一个实例。
在页面上请求数据库的过程中,由于数据库中有多个表,所以多次new数据库类会浪费资源,所以使用单例模式来解决这个问题。
单例模式代码如下所示:
class Single { private static $_instance; private function __construct() { } private function __clone() { } public static function getInstance() { if (!self::$_instance instanceof self) { self::$_instance = new self(); } return self::$_instance; } }