Rumah > pembangunan bahagian belakang > tutorial php > PHP之设计模式(工厂、单例)

PHP之设计模式(工厂、单例)

WBOY
Lepaskan: 2016-07-29 09:02:23
asal
918 orang telah melayarinya

设计模式简单说应对某类问题而设计的解决方式


工厂模式:应对需求创建相应的对象

<code><span><span>class</span><span>factory</span>{</span><span><span>function</span><span>__construct</span><span>(<span>$name</span>)</span>{</span><span>if</span>(file_exists(<span>'./'</span>.<span>$name</span>.<span>'.class.php'</span>)){
            <span>return</span><span>new</span><span>$name</span>;
        }<span>else</span>{
            <span>die</span>(<span>'not exist'</span>);
        }
    }
}</code>
Salin selepas log masuk

单例模式:只创建一个对象的实例,不允许再创建实例,节约资源(例如数据库的连接)

<code><span><span>class</span><span>instance</span>{</span><span>public</span><span>$val</span> = <span>10</span>;
    <span>private</span><span>static</span><span>$instance</span> ;
    <span>private</span><span><span>function</span><span>__construct</span><span>()</span>{</span>}
    <span>private</span><span><span>function</span><span>__clone</span><span>()</span>{</span>}
    <span>//设置为静态方法才可被类调用</span><span>public</span><span>static</span><span><span>function</span><span>getInstance</span><span>()</span>{</span><span>/*if(!isset(self::$instance)){
            self::$instance = new self;
        }*/</span><span>if</span>(!<span>isset</span>(instance::<span>$instance</span>)){
            instance::<span>$instance</span> = <span>new</span><span>self</span>;
        }
        <span>return</span> instance::<span>$instance</span>;
    }
}

<span>$obj_one</span> = instance::getInstance();
<span>$obj_one</span>->val = <span>20</span>;
<span>//clone可以调用__clone()克隆即new出一个新的的对象</span><span>//$obj_two = clone $obj_one;</span><span>$obj_two</span> = instance::getInstance();
<span>echo</span><span>$obj_two</span>->val;
<span>echo</span><span>'<p>'</p></span>;
var_dump(<span>$obj_one</span>,<span>$obj_two</span>);</code>
Salin selepas log masuk

PHP之设计模式(工厂、单例)

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

以上就介绍了PHP之设计模式(工厂、单例),包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan