登录 注册

php单例模式代码示例

收藏
[PHP] 标签:单例模式 2012-10-07 10:24
原始代码 全屏查看 0评 / 0藏 / 5051阅  跳至 / 61行
<?php
 
/**
 * 懒汉式单例类
 */
class Singleton {
 
    /**
     * 静态成品变量 保存全局实例
     */
    private static  $_instance = NULL;
 
    /**
     * 私有化默认构造方法,保证外界无法直接实例化
     */
    private function __construct() {
    }
 
    /**
     * 静态工厂方法,返还此类的唯一实例
     */
    public static function getInstance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new Singleton();
        }
 
        return self::$_instance;
    }
 
    /**
     * 防止用户克隆实例
     */
    public function __clone(){
        die('Clone is not allowed.' . E_USER_ERROR);
    }
 
    /**
     * 测试用方法
     */
    public function test() {
        echo 'Singleton Test!';
    }
 
}
 
/**
 * 客户端
 */
class Client {
 
     /**
     * Main program.
     */
    public static function main() {
        $instance = Singleton::getInstance();
        $instance->test();
    }
}
 
Client::main();
?>

最新评论

  · · · · · ·  (共0条)

目前还没有评论

登录后您才可以发表评论。 马上登录 立即注册
cottage
2012-02-29加入
一段精湛的代码,天涯何处寻知音!
Back to Top