單例模式:
模式:提供建立的靜態方法或在建構函式中建立。常用是靜態方法。
1.建構子私有存取屬性
2.靜態的指向本類的指標
3.靜態的創建自身的方法
以下是php中的實作,getinstall理論上應該加上線程同步,暫未寫。
<code><span><span><?php</span><span><span>class</span><span>myclass</span>{</span><span>public</span><span>static</span><span>$mydata1</span>=<span>NULL</span>; <span>private</span><span><span>function</span><span>__construct</span><span>()</span>{</span><span>echo</span><span>"构造函数<br>"</span>; } <span>public</span><span>static</span><span><span>function</span><span>getinstall</span><span>()</span> {</span><span>if</span> ( <span>self</span>::<span>$mydata1</span>==<span>null</span>) { <span>echo</span><span>"创建对象<br>"</span>; <span>self</span>::<span>$mydata1</span> = <span>new</span> myclass(); } <span>return</span><span>self</span>::<span>$mydata1</span>; } <span>public</span><span><span>function</span><span>test</span><span>()</span> {</span><span>echo</span><span>"hello2<br>"</span>; } } <span>$f</span> = myclass::getinstall(); <span>$f</span>->test(); <span>$f2</span> = myclass::getinstall(); <span>$f2</span>->test(); <span>?></span></span></code>
以上就介紹了 php入門2 單例模式,包含了面向的內容,希望對PHP教學有興趣的朋友有幫助。