zoukankan      html  css  js  c++  java
  • 单例模式小案例

    案例一:

    //创建一个操作数据库的工具类,要求只链接一次数据库
    class DaoMysql{
        //定义需要的属性
        //$mysql_link是数据库链接
        private $mysql_link;
        // $instance是一个静态属性,表示DaoMysql的一个对象实例
        private static $instance = null;
        //构造方法 将构造方法设置为私有
        private function __construct($host,$user,$pwd){
            $this -> mysql_link = @mysql_connect($host,$user,$pwd);
        }
        //写一个静态方法创建对象实例
        public static function getSingleton($host,$user,$pwd){
            //通过 getSingleton来创建对象
            //进行判断如果$instance为空则创建一个对象实例不为空则直接返回$instance
            //instanceof 判断对象实例是否是一个类的对象
            if(!self::$instance instanceof self){
                self:: $instance = new self($host,$user,$pwd); 
            }
            return self:: $instance;
        }
        //阻止克隆
        private function __clone(){}
    }
    $dao1 = DaoMysql::getSingleton('localhost','root','');
    $dao2 = DaoMysql::getSingleton('localhost','root','');
    $dao3 = DaoMysql::getSingleton('localhost','root','');
    $dao4 = DaoMysql::getSingleton('localhost','root','');
    var_dump($dao1,$dao2,$dao3,$dao4);

     案例二:

    class Girl{
        private $name;
        private $age;
        private $stature;
        private static $instance = null;
        private function __construct($name,$age,$stature){
            $this -> name = $name;
            $this -> age = $age;
            $this -> stature = $stature;
        }
        public static function getGirl($name,$age,$stature){
            if(!self::$instance instanceof self){
                self::$instance = new self($name,$age,$stature); 
            }
            return self::$instance;
        }
        private function __clone(){}
    }
    $girl1 = Girl::getGirl('小红',29,160);
    $girl2 = Girl::getGirl('小花',23,162);
    $girl3 = Girl::getGirl('小玲',26,165);
    var_dump($girl1,$girl2,$girl3);
  • 相关阅读:
    移动端高清、多屏适配方案
    Cookie存中文乱码的问题
    手机网站-前端开发布局技巧汇总
    深入理解javascript中的立即执行函数(function(){…})()
    test
    [PAT] A1013 Battle Over Cities (25分)
    PAT索引
    [PAT] A1012 The Best Rank
    [PAT] A1091 Acute Stroke
    [PAT] A1067 Sort with Swap(0, i)
  • 原文地址:https://www.cnblogs.com/rickyctbur/p/11076367.html
Copyright © 2011-2022 走看看