php单例模式的设计与实现

单例模式有三个特点:

1.某个类只能有一个实例。

2.这个类必须自己创建这个实例。

3.这个类必须自行向系统提供这个实例。

<?php
class  Mysql
{
    private $DB;
    static private $_instance;
    // 连接数据库
    private function __construct($host, $username, $password)
    {
        $this->DB = mysql_connect($host, $username, $password);
        $this->query("SET NAMES 'utf8'", $this->link);
        return $this->DB;
    }
    
    private function __clone(){}
    
    public static function getInstance($host, $username, $password)
    {    
        if( !(self::$_instance instanceof self) )
        {
            self::$_instance = new self($host, $username, $password);
        }
        return self::$_instance;
    }
    
    // 连接数据表
    public function select_db($database)
    {
        $this->result = mysql_select_db($database);
        return $this->result;
    }
    
    // 执行SQL语句
    public function query($query)
    {
        return $this->result = mysql_query($query, $this->link);
    }
    
    // 将结果集保存为数组
    public function fetch_array($fetch_array)
    {
        return $this->result = mysql_fetch_array($fetch_array, MYSQL_ASSOC);
    }
    
    // 获得记录数目
    public function num_rows($query)
    {
        return $this->result = mysql_num_rows($query);
    }
    
    // 关闭数据库连接
    public function close()
    {
        return $this->result = mysql_close($this->link);
    }
    
}
?>

  

当然,单例模式不仅仅只是应用在数据库的操作类上面。还可以应用在这些方面:

1. 网站的计数器,一般也是采用单例模式实现,否则难以同步。

2. 应用程序的日志应用,一般都何用单例模式实现,这一般是由于共享的日志文件一直处于打开状态,因为只能有一个实例去操作,否则内容不好追加。

3. Web应用的配置对象的读取,一般也应用单例模式,这个是由于配置文件是共享的资源。

原文地址:https://www.cnblogs.com/cjjjj/p/12499564.html