单例模式要求整个应用程序中一个类只有一个实例,且必须自己创建这个实例,实例提供给全局使用。
单例设计模式在框架中常见的是对数据库的操作。如果不用实例模式每次都需要new操作,这样会消耗大量的内存和系统资源。但是对数据库的操作设计往往涉及设配器模式的设计,故本文采用zend framework1中的Zend_Controller_Front类来说明单例模式。
class Zend_Controller_Front{
protected static $_instance = null;
protected function __construct()
{
$this->_plugins = new Zend_Controller_Plugin_Broker();
}
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
}
构建单例模式需要:
一个保存静态实例的成员变量;
一个只能被自身实例化的构造方法;
一个可以公共访问的静态方法;