php設(shè)計(jì)模式之單例模式代碼
更新時(shí)間:2016年06月11日 09:50:21 作者:dongxiaojie
這篇文章主要為大家詳細(xì)介紹了php設(shè)計(jì)模式之單例模式的實(shí)現(xiàn)代碼,具有一定的參考價(jià)值,感興趣的朋友可以參考一下
php設(shè)計(jì)模式之單例模式的例子,供大家參考,具體內(nèi)容如下
<?php
/**
* php設(shè)計(jì)模式 單例模式
*/
class Fruit{
private static $instanceMap = array();
//protected getter for singleton instances
protected static function getSingleton($className){
//保證單例模式 并且不能從控制器實(shí)例化和克隆
if (!isset(self::$instanceMap[$className])) {
$object = new $className;
//Make sure this object inherit from Singleton
if ($object instanceof Fruit) {
self::$instanceMap[$className] = $object;
var_dump($object);
} else {
throw SingletonException("Class '$className' do not inherit from Singleton!");
}
}
return self::$instanceMap[$className];
}
//protected constructor to prevent outside instantiation
protected function __construct(){}
//denie cloning of singleton objects
public final function __clone(){
trigger_error('It is impossible to clone singleton', E_USER_ERROR);
}
}
class Apple extends Fruit{
protected $rndId;
public function __construct(){
$this->rndId = rand();
}
public function whatAmI(){
echo 'I am a Apple(' . $this->rndId . ')<br />';
}
public static function getInstance(){
//echo get_class();
return Fruit::getSingleton(get_class());
}
}
class GreenApple extends Apple{
public function whatAmI(){
echo 'I am a GreenApple(' . $this->rndId . ')<br />';
}
public static function getInstance(){
return Fruit::getSingleton(get_class());
}
}
$apple1 = Apple::getInstance();
//var_dump($apple1);
$apple2 = GreenApple::getInstance();
$apple1->whatAmI();// should echo 'I am a Apple(some number)
$apple2->whatAmI();// should echo 'I am a GreenApple(some number)
$apple1 = Apple::getInstance();
$apple2 = GreenApple::getInstance();
//保證單例模式
$apple1->whatAmI();// should echo 'I am a Apple(same number as above)
$apple2->whatAmI();// should echo 'I am a GreenApple(same number as above)
// $a = clone $apple1;// this should fail
// $b = clone $apple2;// this should fail
以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)php程序設(shè)計(jì)有所幫助。
相關(guān)文章
php常用字符串查找函數(shù)strstr()與strpos()實(shí)例分析
這篇文章主要介紹了php常用字符串查找函數(shù)strstr()與strpos(),結(jié)合具體實(shí)例形式分析了php字符串查找函數(shù)strstr()與strpos()的具體功能、用法、區(qū)別及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下2019-06-06
Linux下CoreSeek及PHP擴(kuò)展模塊的安裝
前提條件是系統(tǒng)己安裝完成apache mysql php的WEB服務(wù)。我是以yum來安裝的。如果你沒有安裝過請按照下面給出的鏈接先完成基本的LAMP環(huán)境的安裝2012-09-09
php上傳圖片到指定位置路徑保存到數(shù)據(jù)庫的具體實(shí)現(xiàn)
本文為大家介紹下php上傳圖片到指定位置路徑保存到數(shù)據(jù)庫的具體實(shí)現(xiàn),感興趣的朋友不要錯(cuò)過2013-12-12
詳解PHP的Laravel框架中Eloquent對象關(guān)系映射使用
這篇文章主要介紹了PHP的Laravel框架中Eloquent對象關(guān)系映射使用,重點(diǎn)講述了Eloquent的數(shù)據(jù)模型間關(guān)系,需要的朋友可以參考下2016-02-02

