php设计模式 1单例模式

      之前很长时间之前就学习过设计模式,但是因为在实践中很少应用,所以忽略了,但现在却意识到设计模式很重要的,程序设计简介高效冗余性代码少。

      今天开始把前几天学习的几个设计模式整理一下,首先当然是单例模式。

单例模式:

简单的说,一个对象(在学习设计模式之前,需要比较了解面向对象思想)只负责一个特定的任务;

单例类:

1、构造函数需要标记为private(访问控制:防止外部代码使用new操作符创建对象),单例类不能在其他类中实例化,只能被其自身实例化;

2、拥有一个保存类的实例的静态成员变量;

3、拥有一个访问这个实例的公共的静态方法(常用getInstance()方法进行实例化单例类,通过instanceof操作符可以检测到类是否已经被实例化);

4、需要创建__clone()方法防止对象被复制(克隆);

下面来看一下代码实现:

index.php文件

<?php 
require './conn.class.php';
class singletonconn{
    private static $instance;
    private static  function connection() {
        echo '该方法是内部方法,外部无法访问';
        $conn = new conn ();
        $conn->connection
        ( '3306', 'test', '127.0.0.1', 'root', '' );
        return $conn->con;
        
    }
    public static function getcon() {
        if (! isset ( self::$instance )) {
            self::$instance=self::connection();
        }
        return self::$instance;
    }
    public function __toString()
    {
        echo 'ok';
    }
    
    // 阻止用户复制对象实例
    private function __clone() {
        // 用户自定义的错误
        trigger_error ( 'Clone is not allow', E_USER_ERROR );
    }
    
}

$conn=singletonconn::getcon();
$result=$conn->query('select * from test');
while ( $row  =  mysql_fetch_array ( $result ,  MYSQL_NUM )) {
         printf  ( "ID: %s  Name: %s" ,  $row [ 0 ],  $row [ 1 ]);
    }

?>

conn.php 数据库连接类

<?php

class conn{
    private  $con;
    public function connection($port, $db, $host, $user, $pwd) {
        $this->con = mysql_connect( $host,$user,$pwd);
        if (!$this->con){
             $this->con=$this->ErrorMsg();
        }
        if(mysql_select_db ($db,$this->con)){
             $this->conn=$this->ErrorMsg();
        }    
    }

    public function  __get($name){
         return $this->$name;
     }
         
    public function query($sql) {
        $query=mysql_query($sql,$this->con); 
        if (!$query){
            return $this->ErrorMsg();
        }else{
            return $query;
        }
    }
    
    public function close(){
        mysql_close ( $this->con );
    }
    
    /*数据库报错处理*/
    private function ErrorMsg($message = '') {
        if ($message) {
            return $message;
        } else {
            return @mysql_error ();
        }
    }
}
posted @ 2014-07-17 22:47  timelesszhuang  阅读(184)  评论(0编辑  收藏  举报