PHP設(shè)計模式 注冊表模式(多個類的注冊)
更新時間:2012年02月05日 21:49:53 作者:
注冊表模式其實是一個單例模式,注冊表類提供靜態(tài)方法(或單例對象的實例化方法)來讓其它對象訪問其中的數(shù)據(jù)(通常是對象)。整個系統(tǒng)中的每個對象都可以訪問這些數(shù)據(jù)對象
以前我也寫過一個注冊表類,不過那一個不能進行多個類的注冊,下面用數(shù)組對類進行了存儲。
<?php
//基礎(chǔ)類
class webSite {//一個非常簡單的基礎(chǔ)類
private $siteName;
private $siteUrl;
function __construct($siteName,$siteUrl){
$this->siteName=$siteName;
$this->siteUrl=$siteUrl;
}
function getName(){
return $this->siteName;
}
function getUrl(){
return $this->siteUrl;
}
}
class registry {//注冊表類 單例模式
private static $instance;
private $values=array();//用數(shù)組存放類名稱
private function __construct(){}//這個用法決定了這個類不能直接實例化
static function instance(){
if (!isset(self::$instance)){self::$instance=new self();}
return self::$instance;
}
function get($key){//獲取已經(jīng)注冊了的類
if (isset($this->values[$key])){
return $this->values[$key];
}
return null;
}
function set($key,$value){//注冊類方法
$this->values[$key]=$value;
}
}
$reg=registry::instance();
$reg->set("website",new webSite("WEB開發(fā)筆記","www.chhua.com"));//對類進行注冊
$website=$reg->get("website");//獲取類
echo $website->getName();//輸出WEB開發(fā)筆記
echo $website->getUrl();//輸出www.chhua.com
?>
注冊表的作用是提供系統(tǒng)級別的對象訪問功能。有的同學(xué)會說,這樣是多此一舉,不過小項目中的確沒有必要對類進行注冊,如果是大項目,還是非常有用的。
復(fù)制代碼 代碼如下:
<?php
//基礎(chǔ)類
class webSite {//一個非常簡單的基礎(chǔ)類
private $siteName;
private $siteUrl;
function __construct($siteName,$siteUrl){
$this->siteName=$siteName;
$this->siteUrl=$siteUrl;
}
function getName(){
return $this->siteName;
}
function getUrl(){
return $this->siteUrl;
}
}
class registry {//注冊表類 單例模式
private static $instance;
private $values=array();//用數(shù)組存放類名稱
private function __construct(){}//這個用法決定了這個類不能直接實例化
static function instance(){
if (!isset(self::$instance)){self::$instance=new self();}
return self::$instance;
}
function get($key){//獲取已經(jīng)注冊了的類
if (isset($this->values[$key])){
return $this->values[$key];
}
return null;
}
function set($key,$value){//注冊類方法
$this->values[$key]=$value;
}
}
$reg=registry::instance();
$reg->set("website",new webSite("WEB開發(fā)筆記","www.chhua.com"));//對類進行注冊
$website=$reg->get("website");//獲取類
echo $website->getName();//輸出WEB開發(fā)筆記
echo $website->getUrl();//輸出www.chhua.com
?>
注冊表的作用是提供系統(tǒng)級別的對象訪問功能。有的同學(xué)會說,這樣是多此一舉,不過小項目中的確沒有必要對類進行注冊,如果是大項目,還是非常有用的。
相關(guān)文章
PHP面向?qū)ο笪宕笤瓌t之開放-封閉原則(OCP)詳解
這篇文章主要介紹了PHP面向?qū)ο笪宕笤瓌t之開放-封閉原則(OCP),簡單分析了PHP面向?qū)ο箝_放-封閉原則(OCP)的概念、原理、使用方法及相關(guān)注意事項,需要的朋友可以參考下2018-04-04PHP set_error_handler()函數(shù)使用詳解(示例)
本文詳細介紹PHP set_error_handler()函數(shù)的使用方法,最后還提供了一個實例2013-11-11php中unlink()、mkdir()、rmdir()等方法的使用介紹
unlink()函數(shù)刪除文件 、mkdir()函數(shù)創(chuàng)建目錄、rmdir()函數(shù)刪除目錄這些方法在文件相關(guān)的處理方法會經(jīng)常使用到,本文整理了一些,需要的朋友可以了解下2012-12-12PHP人民幣金額數(shù)字轉(zhuǎn)中文大寫的函數(shù)代碼
在網(wǎng)上看到一個非常有趣的PHP人民幣金額數(shù)字轉(zhuǎn)中文大寫的函數(shù),其實質(zhì)就是數(shù)字轉(zhuǎn)換成中文大寫,測試了一下,非常有趣,隨便輸個數(shù)字,就可以將其大寫打印出來,新手朋友們試一下吧2013-02-02