• 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 ();
            }
        }
    }
  • 相关阅读:
    iOS6和iOS7代码的适配(5)——popOver
    es5创建对象与继承
    js学习日记-new Object和Object.create到底干了啥
    js滚动及可视区域的相关的操作
    css匹配规则及性能
    normalize.css源码分析
    css的水平居中和垂直居中总结
    js快速排序算法
    数据结构flash演示
    二叉树遍历
  • 原文地址:https://www.cnblogs.com/timelesszhuang/p/3852340.html
Copyright © 2020-2023  润新知