php 单例模式

来源:互联网 发布:中国地质图书馆 知乎 编辑:程序博客网 时间:2024/06/05 19:05

单例模式的设计

1.      内容:

a)      单例模式是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案

2.      要素:

a)        需要一个保存类的唯一实例的静态成员变量

b)        构造函数和克隆函数声明为私有的,防止外部程序new类从而失去单例模式的意义(单例模式,有时候只是为类提供单例的方式)

c)        必须提供一个访问这个实例的公共的静态方法(通常为getInstance方法),从而返回唯一实例的一个引用

 

3.      设计:

Test.php(设计php):

<?php

    namespace home;

    class test{

        private static $_instance;

        /**

        *   构造方法

        */

        private function __construct(){}

        /**

        *   覆盖clone,禁止克隆

        */

        private function __clone(){}

        /**

        *   获得单个实例

        */

        public static functiongetInstance(){

            if(!(self::$_instanceinstanceof self)){   

                self::$_instance =new self();   

            } 

            return self::$_instance

        }

        public function test(){

            echo memory_get_usage(),'<br>';

        }

    }

?>

 

4.      测试:

Index.php(测试php):

<?php 

    use home\test;

    use home\test1;

    /**

    *   单例模式测试类

    */

    class Index {

        public function run(){

            spl_autoload_register(array($this,'loadClass'));

            $instance= test::getInstance();

            $instance->test();

            $instance_1= test::getInstance();

            $instance_1->test();

            $instance_2= test::getInstance();

            $instance_2->test();

           

            $test1= new test1();

            $test1->test();

            $test1_1= new test1();

            $test1_1->test();

            $test1_2= new test1();

            $test1_2->test();          

        }

        public static functionloadClass($class) {  

            $file= $class . '.php'

            if (is_file($file)) {  

                require_once($file);  

            }  

        }  

    }

    $in= new Index();

    $in->run();

?>

 

结果:

142600
142600
142600
144712
144768
144824

前3行数字为使用单例所占内存,使用3次对象时所占内存的大小一样

后3行数字为正常实例所占内存,使用3次对象时所占内存会逐次变大

 

附录:

1.      用来作比对的test1.php

<?php

    namespace home;

    class test1{

        private static $_instance;

        /**

        *   构造方法

        */

        public function __construct(){}

       

        public function test(){

            echo memory_get_usage(),'<br>';

        }

    }

   

?>

2.      私有构造方法的作用是防止new对象,在项目中一般只要求提供单例的方式,而不硬性规定只要一个对象,所以构造方法一般不要求私有

/**

*   构造方法

*/

private function __construct(){}

 

3.      __clone()私有clone()的作用是防止对象被clone,多产生一个对象,在项目中一般只要求提供单例的方式,而不硬性规定只要一个对象,所以clone一般不要求私有

/**

*   覆盖clone,禁止克隆

*/

private function __clone(){}


0 0
原创粉丝点击