• PHP设计模式系列


    • 单例模式

    通过提供自身共享实例的访问,单例设计模式用于限制特定对象只能被创建一次。

    • 使用场景
    1. 例如数据库实例,一般都会走单例模式。
    2. 单例模式可以减少类的实例化
    • 代码:来源InitPHP框架,先检测类有没被实例化,实例化了就使用已经存放在静态变量中的对象实例,没有则实例化并将对象保存起来。
        /** 
         * 框架核心加载-框架的所有类都需要通过该函数出去 
         * 1. 单例模式 
         * 2. 可以加载-Controller,Service,View,Dao,Util,Library中的类文件 
         * 3. 框架加载核心函数 
         * 使用方法:$this->load($class_name, $type) 
         * @param string $class_name 类名称 
         * @param string $type 类别 
         */  
        public function load($class_name, $type) {  
            $class_path = $this->get_class_path($class_name, $type);  
            $class_name = $this->get_class_name($class_name);  
            if (!file_exists($class_path)) InitPHP::initError('file '. $class_name . '.php is not exist!');  
            if (!isset(self::$instance['initphp'][$class_name])) {  
                require_once($class_path);  
                if (!class_exists($class_name)) InitPHP::initError('class' . $class_name . ' is not exist!');  
                $init_class = new $class_name;  
                self::$instance['initphp'][$class_name] = $init_class;  
            }  
            return self::$instance['initphp'][$class_name];  
        }  

    转自:http://blog.csdn.net/initphp/article/details/7755765

  • 相关阅读:
    洛谷 P1236 算24点
    洛谷 P1483 序列变换
    洛谷 P2071 座位安排 seat.cpp/c/pas
    洛谷 P3079 [USACO13MAR]农场的画Farm Painting
    洛谷 P3912 素数个数
    洛谷 P1617 爱与愁的一千个伤心的理由
    洛谷 P1894 [USACO4.2]完美的牛栏The Perfect Stall
    hdu_5908_Abelian Period(暴力)
    hdu_4283_You Are the One(区间DP)
    hdu_5903_Square Distance(dp)
  • 原文地址:https://www.cnblogs.com/zhhtao/p/4414524.html
Copyright © 2020-2023  润新知