<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    JAVA學(xué)習(xí)點(diǎn)點(diǎn)滴滴

    用開(kāi)放的腦子去闖蕩;用開(kāi)闊的視野去拼搏;用平和的身心去磨練;用美好的理想去追求!

      BlogJava :: 首頁(yè) :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
      18 隨筆 :: 1 文章 :: 2 評(píng)論 :: 0 Trackbacks

    2007年1月21日 #

    創(chuàng)建型模式

    1、FACTORY—追MM少不了請(qǐng)吃飯了,麥當(dāng)勞的雞翅和肯德基的雞翅都是MM愛(ài)吃的東西,雖然口味有所不同,但不管你帶MM去麥當(dāng)勞或肯德基,只管向服務(wù)員說(shuō)“來(lái)四個(gè)雞翅”就行了。麥當(dāng)勞和肯德基就是生產(chǎn)雞翅的Factory

    工廠(chǎng)模式:客戶(hù)類(lèi)和工廠(chǎng)類(lèi)分開(kāi)。消費(fèi)者任何時(shí)候需要某種產(chǎn)品,只需向工廠(chǎng)請(qǐng)求即可。消費(fèi)者無(wú)須修改就可以接納新產(chǎn)品。缺點(diǎn)是當(dāng)產(chǎn)品修改時(shí),工廠(chǎng)類(lèi)也要做相應(yīng)的修改。如:如何創(chuàng)建及如何向客戶(hù)端提供。

    2、BUILDER—MM最?lèi)?ài)聽(tīng)的就是“我愛(ài)你”這句話(huà)了,見(jiàn)到不同地方的MM,要能夠用她們的方言跟她說(shuō)這句話(huà)哦,我有一個(gè)多種語(yǔ)言翻譯機(jī),上面每種語(yǔ)言都有一個(gè)按鍵,見(jiàn)到MM我只要按對(duì)應(yīng)的鍵,它就能夠用相應(yīng)的語(yǔ)言說(shuō)出“我愛(ài)你”這句話(huà)了,國(guó)外的MM也可以輕松搞掂,這就是我的“我愛(ài)你”builder。(這一定比美軍在伊拉克用的翻譯機(jī)好賣(mài))

    建造模式:將產(chǎn)品的內(nèi)部表象和產(chǎn)品的生成過(guò)程分割開(kāi)來(lái),從而使一個(gè)建造過(guò)程生成具有不同的內(nèi)部表象的產(chǎn)品對(duì)象。建造模式使得產(chǎn)品內(nèi)部表象可以獨(dú)立的變化,客戶(hù)不必知道產(chǎn)品內(nèi)部組成的細(xì)節(jié)。建造模式可以強(qiáng)制實(shí)行一種分步驟進(jìn)行的建造過(guò)程。

    3、FACTORY METHOD—請(qǐng)MM去麥當(dāng)勞吃漢堡,不同的MM有不同的口味,要每個(gè)都記住是一件煩人的事情,我一般采用Factory Method模式,帶著MM到服務(wù)員那兒,說(shuō)“要一個(gè)漢堡”,具體要什么樣的漢堡呢,讓MM直接跟服務(wù)員說(shuō)就行了。

    工廠(chǎng)方法模式:核心工廠(chǎng)類(lèi)不再負(fù)責(zé)所有產(chǎn)品的創(chuàng)建,而是將具體創(chuàng)建的工作交給子類(lèi)去做,成為一個(gè)抽象工廠(chǎng)角色,僅負(fù)責(zé)給出具體工廠(chǎng)類(lèi)必須實(shí)現(xiàn)的接口,而不接觸哪一個(gè)產(chǎn)品類(lèi)應(yīng)當(dāng)被實(shí)例化這種細(xì)節(jié)。

    4、PROTOTYPE—跟MM用QQ聊天,一定要說(shuō)些深情的話(huà)語(yǔ)了,我搜集了好多肉麻的情話(huà),需要時(shí)只要copy出來(lái)放到QQ里面就行了,這就是我的情話(huà)prototype了。(100塊錢(qián)一份,你要不要)

    原始模型模式:通過(guò)給出一個(gè)原型對(duì)象來(lái)指明所要?jiǎng)?chuàng)建的對(duì)象的類(lèi)型,然后用復(fù)制這個(gè)原型對(duì)象的方法創(chuàng)建出更多同類(lèi)型的對(duì)象。原始模型模式允許動(dòng)態(tài)的增加或減少產(chǎn)品類(lèi),產(chǎn)品類(lèi)不需要非得有任何事先確定的等級(jí)結(jié)構(gòu),原始模型模式適用于任何的等級(jí)結(jié)構(gòu)。缺點(diǎn)是每一個(gè)類(lèi)都必須配備一個(gè)克隆方法。

    5、SINGLETON—俺有6個(gè)漂亮的老婆,她們的老公都是我,我就是我們家里的老公Sigleton,她們只要說(shuō)道“老公”,都是指的同一個(gè)人,那就是我(剛才做了個(gè)夢(mèng)啦,哪有這么好的事)

    單例模式:?jiǎn)卫J酱_保某一個(gè)類(lèi)只有一個(gè)實(shí)例,而且自行實(shí)例化并向整個(gè)系統(tǒng)提供這個(gè)實(shí)例單例模式。單例模式只應(yīng)在有真正的“單一實(shí)例”的需求時(shí)才可使用。

    結(jié)構(gòu)型模式

    6、ADAPTER—在朋友聚會(huì)上碰到了一個(gè)美女Sarah,從香港來(lái)的,可我不會(huì)說(shuō)粵語(yǔ),她不會(huì)說(shuō)普通話(huà),只好求助于我的朋友kent了,他作為我和Sarah之間的Adapter,讓我和Sarah可以相互交談了(也不知道他會(huì)不會(huì)耍我)

    適配器(變壓器)模式:把一個(gè)類(lèi)的接口變換成客戶(hù)端所期待的另一種接口,從而使原本因接口原因不匹配而無(wú)法一起工作的兩個(gè)類(lèi)能夠一起工作。適配類(lèi)可以根據(jù)參數(shù)返還一個(gè)合適的實(shí)例給客戶(hù)端。

    7、BRIDGE—早上碰到MM,要說(shuō)早上好,晚上碰到MM,要說(shuō)晚上好;碰到MM穿了件新衣服,要說(shuō)你的衣服好漂亮哦,碰到MM新做的發(fā)型,要說(shuō)你的頭發(fā)好漂亮哦。不要問(wèn)我“早上碰到MM新做了個(gè)發(fā)型怎么說(shuō)”這種問(wèn)題,自己用BRIDGE組合一下不就行了

    橋梁模式:將抽象化與實(shí)現(xiàn)化脫耦,使得二者可以獨(dú)立的變化,也就是說(shuō)將他們之間的強(qiáng)關(guān)聯(lián)變成弱關(guān)聯(lián),也就是指在一個(gè)軟件系統(tǒng)的抽象化和實(shí)現(xiàn)化之間使用組合/聚合關(guān)系而不是繼承關(guān)系,從而使兩者可以獨(dú)立的變化。

    8、COMPOSITE—Mary今天過(guò)生日。“我過(guò)生日,你要送我一件禮物。”“嗯,好吧,去商店,你自己挑。”“這件T恤挺漂亮,買(mǎi),這條裙子好看,買(mǎi),這個(gè)包也不錯(cuò),買(mǎi)。”“喂,買(mǎi)了三件了呀,我只答應(yīng)送一件禮物的哦。”“什么呀,T恤加裙子加包包,正好配成一套呀,小姐,麻煩你包起來(lái)。”“……”,MM都會(huì)用Composite模式了,你會(huì)了沒(méi)有?

    合成模式:合成模式將對(duì)象組織到樹(shù)結(jié)構(gòu)中,可以用來(lái)描述整體與部分的關(guān)系。合成模式就是一個(gè)處理對(duì)象的樹(shù)結(jié)構(gòu)的模式。合成模式把部分與整體的關(guān)系用樹(shù)結(jié)構(gòu)表示出來(lái)。合成模式使得客戶(hù)端把一個(gè)個(gè)單獨(dú)的成分對(duì)象和由他們復(fù)合而成的合成對(duì)象同等看待。

    9、DECORATOR—Mary過(guò)完輪到Sarly過(guò)生日,還是不要叫她自己挑了,不然這個(gè)月伙食費(fèi)肯定玩完,拿出我去年在華山頂上照的照片,在背面寫(xiě)上“最好的的禮物,就是愛(ài)你的Fita”,再到街上禮品店買(mǎi)了個(gè)像框(賣(mài)禮品的MM也很漂亮哦),再找隔壁搞美術(shù)設(shè)計(jì)的Mike設(shè)計(jì)了一個(gè)漂亮的盒子裝起來(lái)……,我們都是Decorator,最終都在修飾我這個(gè)人呀,怎么樣,看懂了嗎?

    裝飾模式:裝飾模式以對(duì)客戶(hù)端透明的方式擴(kuò)展對(duì)象的功能,是繼承關(guān)系的一個(gè)替代方案,提供比繼承更多的靈活性。動(dòng)態(tài)給一個(gè)對(duì)象增加功能,這些功能可以再動(dòng)態(tài)的撤消。增加由一些基本功能的排列組合而產(chǎn)生的非常大量的功能。

    10、FACADE—我有一個(gè)專(zhuān)業(yè)的Nikon相機(jī),我就喜歡自己手動(dòng)調(diào)光圈、快門(mén),這樣照出來(lái)的照片才專(zhuān)業(yè),但MM可不懂這些,教了半天也不會(huì)。幸好相機(jī)有Facade設(shè)計(jì)模式,把相機(jī)調(diào)整到自動(dòng)檔,只要對(duì)準(zhǔn)目標(biāo)按快門(mén)就行了,一切由相機(jī)自動(dòng)調(diào)整,這樣MM也可以用這個(gè)相機(jī)給我拍張照片了。

    門(mén)面模式:外部與一個(gè)子系統(tǒng)的通信必須通過(guò)一個(gè)統(tǒng)一的門(mén)面對(duì)象進(jìn)行。門(mén)面模式提供一個(gè)高層次的接口,使得子系統(tǒng)更易于使用。每一個(gè)子系統(tǒng)只有一個(gè)門(mén)面類(lèi),而且此門(mén)面類(lèi)只有一個(gè)實(shí)例,也就是說(shuō)它是一個(gè)單例模式。但整個(gè)系統(tǒng)可以有多個(gè)門(mén)面類(lèi)。

    11、FLYWEIGHT—每天跟MM發(fā)短信,手指都累死了,最近買(mǎi)了個(gè)新手機(jī),可以把一些常用的句子存在手機(jī)里,要用的時(shí)候,直接拿出來(lái),在前面加上MM的名字就可以發(fā)送了,再不用一個(gè)字一個(gè)字敲了。共享的句子就是Flyweight,MM的名字就是提取出來(lái)的外部特征,根據(jù)上下文情況使用。

    享元模式:FLYWEIGHT在拳擊比賽中指最輕量級(jí)。享元模式以共享的方式高效的支持大量的細(xì)粒度對(duì)象。享元模式能做到共享的關(guān)鍵是區(qū)分內(nèi)蘊(yùn)狀態(tài)和外蘊(yùn)狀態(tài)。內(nèi)蘊(yùn)狀態(tài)存儲(chǔ)在享元內(nèi)部,不會(huì)隨環(huán)境的改變而有所不同。外蘊(yùn)狀態(tài)是隨環(huán)境的改變而改變的。外蘊(yùn)狀態(tài)不能影響內(nèi)蘊(yùn)狀態(tài),它們是相互獨(dú)立的。將可以共享的狀態(tài)和不可以共享的狀態(tài)從常規(guī)類(lèi)中區(qū)分開(kāi)來(lái),將不可以共享的狀態(tài)從類(lèi)里剔除出去。客戶(hù)端不可以直接創(chuàng)建被共享的對(duì)象,而應(yīng)當(dāng)使用一個(gè)工廠(chǎng)對(duì)象負(fù)責(zé)創(chuàng)建被共享的對(duì)象。享元模式大幅度的降低內(nèi)存中對(duì)象的數(shù)量。

    12、PROXY—跟MM在網(wǎng)上聊天,一開(kāi)頭總是“hi,你好”,“你從哪兒來(lái)呀?”“你多大了?”“身高多少呀?”這些話(huà),真煩人,寫(xiě)個(gè)程序做為我的Proxy吧,凡是接收到這些話(huà)都設(shè)置好了自動(dòng)的回答,接收到其他的話(huà)時(shí)再通知我回答,怎么樣,酷吧。

    代理模式:代理模式給某一個(gè)對(duì)象提供一個(gè)代理對(duì)象,并由代理對(duì)象控制對(duì)源對(duì)象的引用。代理就是一個(gè)人或一個(gè)機(jī)構(gòu)代表另一個(gè)人或者一個(gè)機(jī)構(gòu)采取行動(dòng)。某些情況下,客戶(hù)不想或者不能夠直接引用一個(gè)對(duì)象,代理對(duì)象可以在客戶(hù)和目標(biāo)對(duì)象直接起到中介的作用。客戶(hù)端分辨不出代理主題對(duì)象與真實(shí)主題對(duì)象。代理模式可以并不知道真正的被代理對(duì)象,而僅僅持有一個(gè)被代理對(duì)象的接口,這時(shí)候代理對(duì)象不能夠創(chuàng)建被代理對(duì)象,被代理對(duì)象必須有系統(tǒng)的其他角色代為創(chuàng)建并傳入。

    行為模式

    13、CHAIN OF RESPONSIBLEITY—晚上去上英語(yǔ)課,為了好開(kāi)溜坐到了最后一排,哇,前面坐了好幾個(gè)漂亮的MM哎,找張紙條,寫(xiě)上“Hi,可以做我的女朋友嗎?如果不愿意請(qǐng)向前傳”,紙條就一個(gè)接一個(gè)的傳上去了,糟糕,傳到第一排的MM把紙條傳給老師了,聽(tīng)說(shuō)是個(gè)老處女呀,快跑!

    責(zé)任鏈模式:在責(zé)任鏈模式中,很多對(duì)象由每一個(gè)對(duì)象對(duì)其下家的引用而接

    起來(lái)形成一條鏈。請(qǐng)求在這個(gè)鏈上傳遞,直到鏈上的某一個(gè)對(duì)象決定處理此請(qǐng)求。客戶(hù)并不知道鏈上的哪一個(gè)對(duì)象最終處理這個(gè)請(qǐng)求,系統(tǒng)可以在不影響客戶(hù)端的情況下動(dòng)態(tài)的重新組織鏈和分配責(zé)任。處理者有兩個(gè)選擇:承擔(dān)責(zé)任或者把責(zé)任推給下家。一個(gè)請(qǐng)求可以最終不被任何接收端對(duì)象所接受。
    14、COMMAND—俺有一個(gè)MM家里管得特別嚴(yán),沒(méi)法見(jiàn)面,只好借助于她弟弟在我們倆之間傳送信息,她對(duì)我有什么指示,就寫(xiě)一張紙條讓她弟弟帶給我。這不,她弟弟又傳送過(guò)來(lái)一個(gè)COMMAND,為了感謝他,我請(qǐng)他吃了碗雜醬面,哪知道他說(shuō):“我同時(shí)給我姐姐三個(gè)男朋友送COMMAND,就數(shù)你最小氣,才請(qǐng)我吃面。”,:-(

    命令模式:命令模式把一個(gè)請(qǐng)求或者操作封裝到一個(gè)對(duì)象中。命令模式把發(fā)出命令的責(zé)任和執(zhí)行命令的責(zé)任分割開(kāi),委派給不同的對(duì)象。命令模式允許請(qǐng)求的一方和發(fā)送的一方獨(dú)立開(kāi)來(lái),使得請(qǐng)求的一方不必知道接收請(qǐng)求的一方的接口,更不必知道請(qǐng)求是怎么被接收,以及操作是否執(zhí)行,何時(shí)被執(zhí)行以及是怎么被執(zhí)行的。系統(tǒng)支持命令的撤消。

    15、INTERPRETER—俺有一個(gè)《泡MM真經(jīng)》,上面有各種泡MM的攻略,比如說(shuō)去吃西餐的步驟、去看電影的方法等等,跟MM約會(huì)時(shí),只要做一個(gè)Interpreter,照著上面的腳本執(zhí)行就可以了。

    解釋器模式:給定一個(gè)語(yǔ)言后,解釋器模式可以定義出其文法的一種表示,并同時(shí)提供一個(gè)解釋器。客戶(hù)端可以使用這個(gè)解釋器來(lái)解釋這個(gè)語(yǔ)言中的句子。解釋器模式將描述怎樣在有了一個(gè)簡(jiǎn)單的文法后,使用模式設(shè)計(jì)解釋這些語(yǔ)句。在解釋器模式里面提到的語(yǔ)言是指任何解釋器對(duì)象能夠解釋的任何組合。在解釋器模式中需要定義一個(gè)代表文法的命令類(lèi)的等級(jí)結(jié)構(gòu),也就是一系列的組合規(guī)則。每一個(gè)命令對(duì)象都有一個(gè)解釋方法,代表對(duì)命令對(duì)象的解釋。命令對(duì)象的等級(jí)結(jié)構(gòu)中的對(duì)象的任何排列組合都是一個(gè)語(yǔ)言。

    ?

    16、ITERATOR—我愛(ài)上了Mary,不顧一切的向她求婚。

    Mary:“想要我跟你結(jié)婚,得答應(yīng)我的條件”

    我:“什么條件我都答應(yīng),你說(shuō)吧”

    Mary:“我看上了那個(gè)一克拉的鉆石”

    我:“我買(mǎi),我買(mǎi),還有嗎?”

    Mary:“我看上了湖邊的那棟別墅”

    我:“我買(mǎi),我買(mǎi),還有嗎?”

    Mary:“你的小弟弟必須要有50cm長(zhǎng)”

    我腦袋嗡的一聲,坐在椅子上,一咬牙:“我剪,我剪,還有嗎?”

    ……

    迭代子模式:迭代子模式可以順序訪(fǎng)問(wèn)一個(gè)聚集中的元素而不必暴露聚集的內(nèi)部表象。多個(gè)對(duì)象聚在一起形成的總體稱(chēng)之為聚集,聚集對(duì)象是能夠包容一組對(duì)象的容器對(duì)象。迭代子模式將迭代邏輯封裝到一個(gè)獨(dú)立的子對(duì)象中,從而與聚集本身隔開(kāi)。迭代子模式簡(jiǎn)化了聚集的界面。每一個(gè)聚集對(duì)象都可以有一個(gè)或一個(gè)以上的迭代子對(duì)象,每一個(gè)迭代子的迭代狀態(tài)可以是彼此獨(dú)立的。迭代算法可以獨(dú)立于聚集角色變化。

    17、MEDIATOR—四個(gè)MM打麻將,相互之間誰(shuí)應(yīng)該給誰(shuí)多少錢(qián)算不清楚了,幸虧當(dāng)時(shí)我在旁邊,按照各自的籌碼數(shù)算錢(qián),賺了錢(qián)的從我這里拿,賠了錢(qián)的也付給我,一切就OK啦,俺得到了四個(gè)MM的電話(huà)。

    調(diào)停者模式:調(diào)停者模式包裝了一系列對(duì)象相互作用的方式,使得這些對(duì)象不必相互明顯作用。從而使他們可以松散偶合。當(dāng)某些對(duì)象之間的作用發(fā)生改變時(shí),不會(huì)立即影響其他的一些對(duì)象之間的作用。保證這些作用可以彼此獨(dú)立的變化。調(diào)停者模式將多對(duì)多的相互作用轉(zhuǎn)化為一對(duì)多的相互作用。調(diào)停者模式將對(duì)象的行為和協(xié)作抽象化,把對(duì)象在小尺度的行為上與其他對(duì)象的相互作用分開(kāi)處理。

    18、MEMENTO—同時(shí)跟幾個(gè)MM聊天時(shí),一定要記清楚剛才跟MM說(shuō)了些什么話(huà),不然MM發(fā)現(xiàn)了會(huì)不高興的哦,幸虧我有個(gè)備忘錄,剛才與哪個(gè)MM說(shuō)了什么話(huà)我都拷貝一份放到備忘錄里面保存,這樣可以隨時(shí)察看以前的記錄啦。

    備忘錄模式:備忘錄對(duì)象是一個(gè)用來(lái)存儲(chǔ)另外一個(gè)對(duì)象內(nèi)部狀態(tài)的快照的對(duì)象。備忘錄模式的用意是在不破壞封裝的條件下,將一個(gè)對(duì)象的狀態(tài)捉住,并外部化,存儲(chǔ)起來(lái),從而可以在將來(lái)合適的時(shí)候把這個(gè)對(duì)象還原到存儲(chǔ)起來(lái)的狀態(tài)。

    19、OBSERVER—想知道咱們公司最新MM情報(bào)嗎?加入公司的MM情報(bào)郵件組就行了,tom負(fù)責(zé)搜集情報(bào),他發(fā)現(xiàn)的新情報(bào)不用一個(gè)一個(gè)通知我們,直接發(fā)布給郵件組,我們作為訂閱者(觀(guān)察者)就可以及時(shí)收到情報(bào)啦

    觀(guān)察者模式:觀(guān)察者模式定義了一種一隊(duì)多的依賴(lài)關(guān)系,讓多個(gè)觀(guān)察者對(duì)象同時(shí)監(jiān)聽(tīng)某一個(gè)主題對(duì)象。這個(gè)主題對(duì)象在狀態(tài)上發(fā)生變化時(shí),會(huì)通知所有觀(guān)察者對(duì)象,使他們能夠自動(dòng)更新自己。

    20、STATE—跟MM交往時(shí),一定要注意她的狀態(tài)哦,在不同的狀態(tài)時(shí)她的行為會(huì)有不同,比如你約她今天晚上去看電影,對(duì)你沒(méi)興趣的MM就會(huì)說(shuō)“有事情啦”,對(duì)你不討厭但還沒(méi)喜歡上的MM就會(huì)說(shuō)“好啊,不過(guò)可以帶上我同事么?”,已經(jīng)喜歡上你的MM就會(huì)說(shuō)“幾點(diǎn)鐘?看完電影再去泡吧怎么樣?”,當(dāng)然你看電影過(guò)程中表現(xiàn)良好的話(huà),也可以把MM的狀態(tài)從不討厭不喜歡變成喜歡哦。

    狀態(tài)模式:狀態(tài)模式允許一個(gè)對(duì)象在其內(nèi)部狀態(tài)改變的時(shí)候改變行為。這個(gè)對(duì)象看上去象是改變了它的類(lèi)一樣。狀態(tài)模式把所研究的對(duì)象的行為包裝在不同的狀態(tài)對(duì)象里,每一個(gè)狀態(tài)對(duì)象都屬于一個(gè)抽象狀態(tài)類(lèi)的一個(gè)子類(lèi)。狀態(tài)模式的意圖是讓一個(gè)對(duì)象在其內(nèi)部狀態(tài)改變的時(shí)候,其行為也隨之改變。狀態(tài)模式需要對(duì)每一個(gè)系統(tǒng)可能取得的狀態(tài)創(chuàng)立一個(gè)狀態(tài)類(lèi)的子類(lèi)。當(dāng)系統(tǒng)的狀態(tài)變化時(shí),系統(tǒng)便改變所選的子類(lèi)。

    ?? 21、STRATEGY—跟不同類(lèi)型的MM約會(huì),要用不同的策略,有的請(qǐng)電影比較好,有的則去吃小吃效果不錯(cuò),有的去海邊浪漫最合適,單目的都是為了得到MM的芳心,我的追MM錦囊中有好多Strategy哦。

    策略模式:策略模式針對(duì)一組算法,將每一個(gè)算法封裝到具有共同接口的獨(dú)立的類(lèi)中,從而使得它們可以相互替換。策略模式使得算法可以在不影響到客戶(hù)端的情況下發(fā)生變化。策略模式把行為和環(huán)境分開(kāi)。環(huán)境類(lèi)負(fù)責(zé)維持和查詢(xún)行為類(lèi),各種算法在具體的策略類(lèi)中提供。由于算法和環(huán)境獨(dú)立開(kāi)來(lái),算法的增減,修改都不會(huì)影響到環(huán)境和客戶(hù)端。

    22、TEMPLATE METHOD——看過(guò)《如何說(shuō)服女生上床》這部經(jīng)典文章嗎?女生從認(rèn)識(shí)到上床的不變的步驟分為巧遇、打破僵局、展開(kāi)追求、接吻、前戲、動(dòng)手、愛(ài)撫、進(jìn)去八大步驟(Template method),但每個(gè)步驟針對(duì)不同的情況,都有不一樣的做法,這就要看你隨機(jī)應(yīng)變啦(具體實(shí)現(xiàn));

    模板方法模式:模板方法模式準(zhǔn)備一個(gè)抽象類(lèi),將部分邏輯以具體方法以及具體構(gòu)造子的形式實(shí)現(xiàn),然后聲明一些抽象方法來(lái)迫使子類(lèi)實(shí)現(xiàn)剩余的邏輯。不同的子類(lèi)可以以不同的方式實(shí)現(xiàn)這些抽象方法,從而對(duì)剩余的邏輯有不同的實(shí)現(xiàn)。先制定一個(gè)頂級(jí)邏輯框架,而將邏輯的細(xì)節(jié)留給具體的子類(lèi)去實(shí)現(xiàn)。

    23、VISITOR—情人節(jié)到了,要給每個(gè)MM送一束鮮花和一張卡片,可是每個(gè)MM送的花都要針對(duì)她個(gè)人的特點(diǎn),每張卡片也要根據(jù)個(gè)人的特點(diǎn)來(lái)挑,我一個(gè)人哪搞得清楚,還是找花店老板和禮品店老板做一下Visitor,讓花店老板根據(jù)MM的特點(diǎn)選一束花,讓禮品店老板也根據(jù)每個(gè)人特點(diǎn)選一張卡,這樣就輕松多了;

    訪(fǎng)問(wèn)者模式:訪(fǎng)問(wèn)者模式的目的是封裝一些施加于某種數(shù)據(jù)結(jié)構(gòu)元素之上的操作。一旦這些操作需要修改的話(huà),接受這個(gè)操作的數(shù)據(jù)結(jié)構(gòu)可以保持不變。訪(fǎng)問(wèn)者模式適用于數(shù)據(jù)結(jié)構(gòu)相對(duì)未定的系統(tǒng),它把數(shù)據(jù)結(jié)構(gòu)和作用于結(jié)構(gòu)上的操作之間的耦合解脫開(kāi),使得操作集合可以相對(duì)自由的演化。訪(fǎng)問(wèn)者模式使得增加新的操作變的很容易,就是增加一個(gè)新的訪(fǎng)問(wèn)者類(lèi)。訪(fǎng)問(wèn)者模式將有關(guān)的行為集中到一個(gè)訪(fǎng)問(wèn)者對(duì)象中,而不是分散到一個(gè)個(gè)的節(jié)點(diǎn)類(lèi)中。當(dāng)使用訪(fǎng)問(wèn)者模式時(shí),要將盡可能多的對(duì)象瀏覽邏輯放在訪(fǎng)問(wèn)者類(lèi)中,而不是放到它的子類(lèi)中。訪(fǎng)問(wèn)者模式可以跨過(guò)幾個(gè)類(lèi)的等級(jí)結(jié)構(gòu)訪(fǎng)問(wèn)屬于不同的等級(jí)結(jié)構(gòu)的成員類(lèi)。

    轉(zhuǎn)http://java.ccidnet.com/art/3749/20060622/586221_3.html

    ?

    posted @ 2007-01-27 23:05 海思 閱讀(262) | 評(píng)論 (0)編輯 收藏

    Object Hierarchy and Inheritance in JavaScript

    JavaScript is an object-oriented language based on prototypes, rather than, as is common, being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values. This paper attempts to clarify the situation. If you're interested in precise details of how this all works, you can read the ECMA-262 JavaScript language specification (as a PDF file or a Microsoft Word self-extracting binary).

    This paper assumes that you're already somewhat familiar with JavaScript and that you have used JavaScript functions to create simple objects. For information on this subject, see Chapter 10, "Object Model," in the JavaScript Guide.

    The sections in this paper are:

    Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances. A class defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the Employee class could represent the set of all employees. An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the properties of its parent class (no more, no less).

    A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as a template from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or even at runtime. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.

    In class-based languages, you define a class in a separate class definition. In that definition you can specify special methods, called constructors, to use to create instances of the class. A constructor method can specify initial values for the instance's properties and perform other processing appropriate at creation time. You use the new operator in association with the constructor method to create class instances.

    JavaScript follows a similar model, but does not have a class definition separate from the constructor. Instead, you define a constructor function to create objects with a particular initial set of properties and values. Any JavaScript function can be used as a constructor. You use the new operator with a constructor function to create a new object.

    In a class-based language, you create a hierarchy of classes through the class definitions. In a class definition, you can specify that the new class is a subclass of an already existing class. The subclass inherits all the properties of the superclass and additionally can add new properties or modify the inherited ones. For example, assume the Employee class includes only name and dept properties and Manager is a subclass of Employee that adds the reports property. In this case, an instance of the Manager class would have all three properties: name, dept, and reports.

    JavaScript implements inheritance by allowing you to associate a prototypical object with any constructor function. So, you can create exactly the Employee-Manager example, but you use slightly different terminology. First you define the Employee constructor function, specifying the name and dept properties. Next, you define the Manager constructor function, specifying the reports property. Finally, you assign a new Employee object as the prototype for the Manager constructor function. Then, when you create a new Manager, it inherits the name and dept properties from the Employee object.

    In class-based languages, you typically create a class at compile time and then you instantiate instances of the class either at compile time or at runtime. You cannot change the number or the type of properties of a class after you define the class. In JavaScript, however, at runtime you can add or remove properties from any object. If you add a property to an object that is used as the prototype for a set of objects, the objects for which it is the prototype also get the new property.

    Table?1 gives a short summary of some of these differences. The rest of this paper describes the details of using JavaScript constructors and prototypes to create an object hierarchy and compares this to how you would do it in Java.

    Table 1?Comparison of class-based (Java) and prototype-based (JavaScript) object systems

    Class-based (Java) Prototype-based (JavaScript)
    Class and instance are distinct entities.

    All objects are instances.

    Define a class with a class definition; instantiate a class with constructor methods.

    Define and create a set of objects with constructor functions.

    Create a single object with the new operator.

    Same.

    Construct an object hierarchy by using class definitions to define subclasses of existing classes.

    Construct an object hierarchy by assigning an object as the prototype associated with a constructor function.

    Inherit properties by following the class chain.

    Inherit properties by following the prototype chain.

    Class definition specifies all properties of all instances of a class. No way to add properties dynamically at runtime.

    Constructor function or prototype specifies an initial set of properties. Can add or remove properties dynamically to individual objects or to the entire set of objects.

    The Employee Example

    The rest of this paper works with the simple employee hierarchy shown in Figure 1.

    Figure 1??? A simple object hierarchy

  • Employee has the properties name (whose value defaults to the empty string) and dept (whose value defaults to "general").
  • Manager is based on Employee. It adds the reports property (whose value defaults to an empty array, intended to have an array of Employee objects as its value).

  • WorkerBee is also based on Employee. It adds the projects property (whose value defaults to an empty array, intended to have an array of strings as its value).

  • SalesPerson is based on WorkerBee. It adds the quota property (whose value defaults to 100). It also overrides the dept property with the value "sales", indicating that all salespersons are in the same department.

  • Engineer is based on WorkerBee. It adds the machine property (whose value defaults to the empty string) and also overrides the dept property with the value "engineering".

    Creating the Hierarchy

    There are several ways you can define appropriate constructor functions to implement the Employee hierarchy. How you choose to define them depends largely on what you want to be able to do in your application. We'll get into all that later.

    For now, let's use very simple (and comparatively inflexible) definitions just to see how we get the inheritance to work. In these definitions, you can't specify any property values when you create an object. The newly-created object simply gets the default values, which you can change at a later time. Figure 2 illustrates the hierarchy with these simple definitions.

    In a real application, you would probably define constructors that allow you to provide property values at object creation time. Options for doing so are described later in . For now, these simple definitions let us look at how the inheritance occurs.

    Figure 2??? What the definitions look like

    The simple Java and JavaScript Employee definitions below are similar. The only difference is that you need to specify the type for each property in Java but not in JavaScript and you need to create an explicit constructor method for the Java class.

    JavaScript Java
    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    public class Employee {
    ???public String name;
    ???public String dept;
    ???public Employee () {
    ??????this.name = "";
    ??????this.dept = "general";
    ???}
    }

    The Manager and WorkerBee definitions show the difference in how you specify the next object higher in the inheritance chain. In JavaScript, you add a prototypical instance as the value of the prototype property of the constructor function. You can do so at any time after you define the constructor. In Java, you specify the superclass within the class definition. You cannot change the superclass outside the class definition.

    JavaScript Java
    function Manager () {
    this.reports = [];
    }
    Manager.prototype = new Employee;
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    public class Manager extends Employee {
    ???public Employee[] reports;
    ???public Manager () {
    ??????this.reports = new Employee[0];
    ???}
    }
    public class WorkerBee extends Employee {
    ???public String[] projects;
    ???public WorkerBee () {
    ??????this.projects = new String[0];
    ???}
    }

    The Engineer and SalesPerson definitions create objects that descend from WorkerBee and hence from Employee. An object of these types has properties of all the objects above it in the chain. In addition, these definitions override the inherited value of the dept property with new values specific to these objects.

    JavaScript Java
    function SalesPerson () {
    ???this.dept = "sales";
    ???this.quota = 100;
    }
    SalesPerson.prototype = new WorkerBee;
    function Engineer () {
    ???this.dept = "engineering";
    ???this.machine = "";
    }
    Engineer.prototype = new WorkerBee;
    public class SalesPerson extends WorkerBee {
    ???public double quota;
    ???public SalesPerson () {
    ??????this.dept = "sales";
    ??????this.quota = 100.0;
    ???}
    }
    public class Engineer extends WorkerBee {
    ???public String machine;
    ???public Engineer () {
    ??????this.dept = "engineering";
    ??????this.machine = "";
    ???}
    }

    Using these definitions, you can create instances of these objects that get the default values for their properties. Figure 3 illustrates using these JavaScript definitions to create new objects and shows the property values for the new objects.

    NOTE: As described earlier, the term instance has a specific technical meaning in class-based languages. In these languages, an instance is an individual member of a class and is fundamentally different from a class. In JavaScript, "instance" does not have this technical meaning because JavaScript does not have this difference between classes and instances. However, in talking about JavaScript, "instance" can be used informally to mean an object created using a particular constructor function. So, in this example, you could informally say that jane is an instance of Engineer. Similarly, although the terms parent, child, ancestor, and descendant do not have formal meanings in JavaScript, we can use them informally to refer to objects higher or lower in the prototype chain.
    Figure 3??? Creating objects with the simple definitions

    Object Properties

    This section discusses how objects inherit properties from other objects in the prototype chain and what happens when you add a property at runtime.

    Inheriting Properties

    Assume you create the mark object as a WorkerBee as shown in Figure 3 with this statement:

    mark = new WorkerBee;
    When JavaScript sees the new operator, it creates a new generic object and passes this new object as the value of the this keyword to the WorkerBee constructor function. The constructor function explicitly sets the value of the projects property. It also sets the value of the internal __proto__ property to the value of WorkerBee.prototype. (That property name has 2 underscore characters at the front and 2 at the end.) The __proto__ property determines the prototype chain used to return property values. Once these properties are set, JavaScript returns the new object and the assignment statement sets the variable mark to that object.

    This process doesn't explicitly put values in the mark object (local values) for the properties mark inherits from the prototype chain. When you ask for the value of a property, JavaScript first checks to see if the value exists in that object. If it does, that value is returned. If the value isn't there locally, JavaScript checks the prototype chain (using the __proto__ property). If an object in the prototype chain has a value for the property, that value is returned. If no such property is found, JavaScript says the object doesn't have the property. In this way, the mark object has the following properties and values:

    mark.name = "";
    mark.dept = "general";
    mark.projects = [];
    The mark object inherits values for the name and dept properties from the prototypical object in mark.__proto__. It is assigned a local value for the projects property by the WorkerBee constructor. Simply put, this gives you inheritance of properties and their values in JavaScript. Some subtleties of this process are discussed in .

    Because these constructors don't let you supply instance-specific values, this information is generic. The property values are the default ones shared by all new objects created from WorkerBee. You can, of course, change the values of any of these properties. So, you could give specific information for mark as shown here:

    mark.name = "Doe, Mark";
    mark.dept = "admin";
    mark.projects = ["navigator"];

    Adding Properties

    In JavaScript at runtime you can add properties to any object. You are not constrained to use only the properties provided by the constructor function. To add a property that is specific to a single object, you simply assign a value to the object, as in:

    mark.bonus = 3000;
    Now, the mark object has a bonus property, but no other WorkerBee has this property.

    If you add a new property to an object that is being used as the prototype for a constructor function, you add that property to all objects that inherit properties from the prototype. For example, you can add a specialty property to all employees with the following statement:

    Employee.prototype.specialty = "none";
    As soon as JavaScript executes this statement, the mark object also has the specialty property with the value of "none". Figure 4 shows the effect of adding this property to the Employee prototype and then overriding it for the Engineer prototype.

    Figure 4??? Adding properties

    More Flexible Constructors

    The constructor functions used so far do not let you specify property values when you create an instance. As with Java, you can provide arguments to constructors to initialize property values for instances. Figure 5 shows one way to do this.

    Figure 5??? Specifying properties in a constructor, take 1

    Here are the Java and JavaScript definitions for these objects.

    JavaScript Java
    function Employee (name, dept) {
    this.name = name || "";
    this.dept = dept || "general";
    }
    public class Employee {
    ???public String name;
    ???public String dept;
    ???public Employee () {
    ??????this("", "general");
    ???}
    ???public Employee (name) {
    ??????this(name, "general");
    ???}
    ???public Employee (name, dept) {
    ??????this.name = name;
    ??????this.dept = dept;
    ???}
    }
    function WorkerBee (projs) {
    this.projects = projs || [];
    }
    WorkerBee.prototype = new Employee;
    public class WorkerBee extends Employee {
    ???public String[] projects;
    ???public WorkerBee () {
    ??????this(new String[0]);
    ???}
    ???public WorkerBee (String[] projs) {
    ??????this.projects = projs;
    ???}
    }
    function Engineer (mach) {
    ???this.dept = "engineering";
    ???this.machine = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    public class Engineer extends WorkerBee {
    ???public String machine;
    ???public WorkerBee () {
    ??????this.dept = "engineering";
    ??????this.machine = "";
    ???}
    ???public WorkerBee (mach) {
    ??????this.dept = "engineering";
    ??????this.machine = mach;
    ???}
    }

    These JavaScript definitions use a special idiom for setting default values:

    this.name = name || "";
    The JavaScript logical OR operator (||) evaluates its first argument. If that argument is converts to true, the operator returns it. Otherwise, the operator returns the value of the second argument. Therefore, this line of code tests to see if name has a useful value for the name property. If it does, it sets this.name to that value. Otherwise, it sets this.name to the empty string. This paper uses this idiom for brevity; however, it can be puzzling at first glance.

    With these definitions, when you create an instance of an object, you can specify values for the locally defined properties. As shown in Figure 5, you can use this statement to create a new Engineer:

    jane = new Engineer("belau");
    Jane's properties are now:

    jane.name == "";
    jane.dept == "general";
    jane.projects == [];
    jane.machine == "belau"
    Notice that with these definitions, you cannot specify an initial value for an inherited property such as name. If you want to specify an initial value for inherited properties in JavaScript, you need to add more code to the constructor function.

    So far, the constructor function has created a generic object and then specified local properties and values for the new object. You can have the constructor add more properties by directly calling the constructor function for an object higher in the prototype chain. Figure 6 shows these new definitions.

    Figure 6??? Specifying properties in a constructor, take 2

    Let's look at one of these definitions in detail. Here's the new definition for the Engineer constructor:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Assume we create a new Engineer object as follows:

    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    JavaScript follows these steps:

    1.???First, the new operator creates a generic object and sets its __proto__ property to Engineer.prototype.
    2.???The new operator then passes the new object to the Engineer constructor as the value of the this keyword.
    3.???Next, the constructor creates a new property called base for that object and assigns the value of the WorkerBee constructor to the base property. This makes the WorkerBee constructor a method of the Engineer object.
    NOTE: The name of the base property is not special. You can use any legal property name; base is simply evocative of its purpose.
    4.???Next, the constructor calls the base method, passing as its arguments two of the arguments passed to the constructor ("Doe, Jane" and ["navigator", "javascript"]) and also the string "engineering". Explicitly using "engineering" in the constructor indicates that all Engineer objects have the same value for the inherited dept property and this value overrides the value inherited from Employee.
    5.???Because base is a method of Engineer, within the call to base, JavaScript binds the this keyword to the object created in step?1. Thus, the WorkerBee function in turn passes the "Doe, Jane" and ["navigator", "javascript"] arguments to the Employee constructor function. Upon return from the Employee constructor function, the WorkerBee function uses the remaining argument to set the projects property.
    6.???Upon return from the base method, the Engineer constructor initializes the object's machine property to "belau".
    7.???Upon return from the constructor, JavaScript assigns the new object to the jane variable.
    You might think that, having called the WorkerBee constructor from inside the Engineer constructor, you've set up inheritance appropriately for Engineer objects. This is not the case. Calling the WorkerBee constructor ensures that an Engineer object starts out with the properties specified in all constructor functions that are called. However, if you later add properties to the Employee or WorkerBee prototypes, those properties are not inherited by the Engineer object. For example, assume you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    The jane object does not inherit the specialty property. You still need to explicitly set up the prototype to ensure dynamic inheritance. Assume instead you have these statements:

    function Engineer (name, projs, mach) {
    this.base = WorkerBee;
    this.base(name, "engineering", projs);
    this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau");
    Employee.prototype.specialty = "none";
    Now the value of the jane object's specialty property is "none".

    Property Inheritance Revisited

    The preceding sections have described how constructors and prototypes provide hierarchies and inheritance in JavaScript. As with all languages, there are some subtleties that were not necessarily apparent in these earlier discussions. This section discusses some of those subtleties.

    Local versus Inherited Values

    Let's revisit property inheritance briefly. As discussed earlier, when you access an object property, JavaScript performs these steps:

    1. Check to see if the value exists locally. If it does, return that value.
    2. If there isn't a local value, check the prototype chain (using the __proto__ property).

    3. If an object in the prototype chain has a value for the specified property, return that value.

    4. If no such property is found, the object does not have the property.
    The outcome of this simple set of steps depends on how you've defined things along the way. In our original example, we had these definitions:

    function Employee () {
    this.name = "";
    this.dept = "general";
    }
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    With these definitions, assume you create amy as an instance of WorkerBee with this statement:

    amy = new WorkerBee;
    The amy object has one local property, projects. The values for the name and dept properties are not local to amy and so are gotten from the amy object's __proto__ property. Thus, amy has these property values:

    amy.name == "";
    amy.dept = "general";
    amy.projects == [];
    Now assume you change the value of the name property in the prototype associated with Employee:

    Employee.prototype.name = "Unknown"
    At first glance, you might expect that new value to propagate down to all the instances of Employee. However, it does not.

    When you create any instance of the Employee object, that instance gets a local value for the name property (the empty string). This means that when you set the WorkerBee prototype by creating a new Employee object, WorkerBee.prototype has a local value for the name property. Therefore, when JavaScript looks up the name property of the amy object (an instance of WorkerBee), JavaScript finds the local value for that property in WorkerBee.prototype. It therefore does not look farther up the chain to Employee.prototype.

    If you want to change the value of an object property at runtime and have the new value be inherited by all descendants of the object, you cannot define the property in the object's constructor function. Instead, you add it to the constructor's associated prototype. For example, assume you change the code above to the following:

    function Employee () {
    ???this.dept = "general";
    }
    Employee.prototype.name = "";
    function WorkerBee () {
    this.projects = [];
    }
    WorkerBee.prototype = new Employee;
    amy = new WorkerBee;
    Employee.prototype.name = "Unknown";
    In this case, the name property of amy becomes "Unknown".

    As these examples show, if you want to have default values for object properties and you want to be able to change the default values at runtime, you should set the properties in the constructor's prototype, not in the constructor function itself.

    Determining Instance Relationships

    You may want to know what objects are in the prototype chain for an object, so that you can tell from what objects this object inherits properties. In a class-based language, you might have an instanceof operator for this purpose. JavaScript does not provide instanceof, but you can write such a function yourself.

    As discussed in , when you use the new operator with a constructor function to create a new object, JavaScript sets the __proto__ property of the new object to the value of the prototype property of the constructor function. You can use this to test the prototype chain.

    For example, assume you have the same set of definitions we've been using, with the prototypes set appropriately. Create an __proto__ object as follows:

    chris = new Engineer("Pigman, Chris", ["jsd"], "fiji");
    With this object, the following statements are all true:

    chris.__proto__ == Engineer.prototype;
    chris.__proto__.__proto__ == WorkerBee.prototype;
    chris.__proto__.__proto__.__proto__ == Employee.prototype;
    chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype;
    chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null;
    Given this, you could write an instanceOf function as follows:

    function instanceOf(object, constructor) { 
    ???while (object != null) {
    ??????if (object == constructor.prototype)
    ?????????return true;
    ??????object = object.__proto__;
    ???}
    ???return false;
    }
    With this definition, the following expressions are all true:

    instanceOf (chris, Engineer)
    instanceOf (chris, WorkerBee)
    instanceOf (chris, Employee)
    instanceOf (chris, Object)
    But this expression is false:

    instanceOf (chris, SalesPerson)

    Global Information in Constructors

    When you create constructors, you need to be careful if you set global information in the constructor. For example, assume that you want a unique ID to be automatically assigned to each new employee. You could use this definition for Employee:

    var idCounter = 1;
    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???this.id = idCounter++;
    }
    With this definition, when you create a new Employee, the constructor assigns it the next ID in sequence and then increments the global ID counter. So, if your next statement were:

    victoria = new Employee("Pigbert, Victoria", "pubs")
    harry = new Employee("Tschopik, Harry", "sales")
    victoria.id is 1 and harry.id is 2. At first glance that seems fine. However, idCounter gets incremented every time an Employee object is created, for whatever purpose. If you create the entire Employee hierarchy we've been working with, the Employee constructor is called every time we set up a prototype. That is, assume you have this code:

    var idCounter = 1;
    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???this.id = idCounter++;
    }
    function Manager (name, dept, reports) {...}
    Manager.prototype = new Employee;
    function WorkerBee (name, dept, projs) {...}
    WorkerBee.prototype = new Employee;
    function Engineer (name, projs, mach) {...}
    Engineer.prototype = new WorkerBee;
    function SalesPerson (name, projs, quota) {...}
    SalesPerson.prototype = new WorkerBee;
    mac = new Engineer("Wood, Mac");
    Further assume that the definitions we've omitted here have the base property and call the constructor above them in the prototype chain. In this case, by the time the mac object is created, mac.id is 5.

    Depending on the application, it may or may not matter that the counter has been incremented these extra times. If you care about the exact value of this counter, one possible solution involves instead using this constructor:

    function Employee (name, dept) {
    ???this.name = name || "";
    ???this.dept = dept || "general";
    ???if (name)
    ??????this.id = idCounter++;
    }
    When you create an instance of Employee to use as a prototype, you do not supply arguments to the constructor. Using this definition of the constructor, when you do not supply arguments, the constructor does not assign a value to the id and does not update the counter. Therefore, for an Employee to get an assigned id, you must specify a name for the employee. In our example, mac.id would be 1.

    No Multiple Inheritance

    Some object-oriented languages allow multiple inheritance. That is, an object can inherit the properties and values from unrelated parent objects. JavaScript does not support multiple inheritance.

    As we've already said, inheritance of property values occurs at runtime by JavaScript searching the prototype chain of an object to find a value. Because an object has a single associated prototype, JavaScript cannot dynamically inherit from more than one prototype chain.

    In JavaScript you can have a constructor function call more than one other constructor function within it. This gives the illusion of multiple inheritance. For example, consider the following statements:

    function Hobbyist (hobby) {
    ???this.hobby = hobby || "scuba";
    }
    function Engineer (name, projs, mach, hobby) {
    ???this.base1 = WorkerBee;
    ???this.base1(name, "engineering", projs);
    ???this.base2 = Hobbyist;
    ???this.base2(hobby);
    ???this.projects = mach || "";
    }
    Engineer.prototype = new WorkerBee;
    dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo")
    Further assume that the definition of WorkerBee is as we've previously seen it. In this case, the dennis object has these properties:

    dennis.name == "Doe, Dennis"
    dennis.dept == "engineering"
    dennis.projects == ["collabra"]
    dennis.machine == "hugo"
    dennis.hobby == "scuba"
    So dennis does get the hobby property from the Hobbyist constructor. However, assume you then add a property to the Hobbyist constructor's prototype:

    Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"]
    The dennis object does not inherit this new property.

    Last Updated: 12/18/97 15:19:54


    Copyright ? 1997 Netscape Communications Corporation

  • posted @ 2007-01-21 16:19 海思 閱讀(473) | 評(píng)論 (0)編輯 收藏

    跨越邊界: JavaScript 語(yǔ)言特性

    研究編程語(yǔ)言中的“丑小鴨”

    developerWorks
    文檔選項(xiàng)
    將此頁(yè)作為電子郵件發(fā)送

    將此頁(yè)作為電子郵件發(fā)送

    未顯示需要 JavaScript 的文檔選項(xiàng)

    樣例代碼


    拓展 Tomcat 應(yīng)用

    下載 IBM 開(kāi)源 J2EE 應(yīng)用服務(wù)器 WAS CE 新版本 V1.1


    級(jí)別: 初級(jí)

    Bruce Tate (bruce.tate@j2life.com), 總裁, RapidRed

    2007 年 1 月 18 日

    JavaScript 常被人們認(rèn)為是編程語(yǔ)言中無(wú)足輕重的一員。這種觀(guān)點(diǎn)的形成可以“歸功”于其開(kāi)發(fā)工具、復(fù)雜且不一致的面向 HTML 頁(yè)面的文檔對(duì)象模型以及不一致的瀏覽器實(shí)現(xiàn)。但 JavaScript 絕對(duì)不僅僅是一個(gè)玩具這么簡(jiǎn)單。在本文中,Bruce Tate 向您介紹了 JavaScript 的語(yǔ)言特性。

    幾乎每個(gè) Web 開(kāi)發(fā)人員都曾有過(guò)詛咒 JavaScript 的經(jīng)歷。這個(gè)備受爭(zhēng)議的語(yǔ)言受累于其復(fù)雜的稱(chēng)為文檔對(duì)象模型 (DOM)的編程模型、糟糕的實(shí)現(xiàn)和調(diào)試工具以及不一致的瀏覽器實(shí)現(xiàn)。直到最近,很多開(kāi)發(fā)人員還認(rèn)為 Javascript 從最好的方面說(shuō)是無(wú)可避免之災(zāi)禍,從最壞的方面說(shuō)不過(guò)是一種玩具罷了。

    然而 JavaScript 現(xiàn)在開(kāi)始日益重要起來(lái),而且成為了廣泛應(yīng)用于 Web 開(kāi)發(fā)的腳本語(yǔ)言。JavaScript 的復(fù)蘇使一些業(yè)界領(lǐng)袖人物也不得不開(kāi)始重新審視這種編程語(yǔ)言。諸如 Ajax (Asynchronous JavaScript + XML) 這樣的編程技術(shù)讓 Web 網(wǎng)頁(yè)更加迷人。而完整的 Web 開(kāi)發(fā)框架,比如 Apache Cocoon,則讓 JavaScript 的應(yīng)用越來(lái)越多,使其不只限于是一種用于制作 Web 頁(yè)面的簡(jiǎn)單腳本。JavaScript 的一種稱(chēng)為 ActionScript 的派生物也推動(dòng)了 Macromedia 的 Flash 客戶(hù)端框架的發(fā)展。運(yùn)行在 JVM 上的實(shí)現(xiàn) Rhino 讓 JavaScript 成為了 Java? 開(kāi)發(fā)人員所首選的一類(lèi)腳本語(yǔ)言(參見(jiàn) 參考資料)。

    我的好友兼同事 Stuart Halloway 是 Ajax 方面的專(zhuān)家,曾在其教授的 JavaScript 課程中做過(guò)這樣的開(kāi)場(chǎng)白:“到 2011 年,JavaScript 將被公認(rèn)為是一種擁有開(kāi)發(fā)現(xiàn)代應(yīng)用程序所需的一整套新特性的語(yǔ)言” 。他繼而介紹說(shuō) JavaScript 程序要比類(lèi)似的 Java 程序緊密十倍,并繼續(xù)展示了使其之所以如此的一些語(yǔ)言特性。

    關(guān)于這個(gè)系列

    跨越邊界系列中,作者 Bruce Tate 提出了這樣一個(gè)主張:今天的 Java 程序員通過(guò)學(xué)習(xí)其他技術(shù)和語(yǔ)言,會(huì)得到很好的幫助。編程領(lǐng)域已經(jīng)發(fā)生了變化,Java 技術(shù)不再是所有開(kāi)發(fā)項(xiàng)目理所當(dāng)然的最佳選擇。其他框架正在影響 Java 框架構(gòu)建的方式,而從其他語(yǔ)言學(xué)到的概念也有助于 Java 編程。對(duì) Python(或 Ruby、Smalltalk 等等)代碼的編寫(xiě)可能改變 Java 編碼的方式。

    這個(gè)系列介紹的編程概念和技術(shù),與 Java 開(kāi)發(fā)有根本的不同,但可以直接應(yīng)用于 Java 編程。在某些情況下,需要集成這些技術(shù)來(lái)利用它們。在其他情況下,可以直接應(yīng)用這些概念。單獨(dú)的工具并不重要,重要的是其他語(yǔ)言和框架可以影響 Java 社區(qū)中的開(kāi)發(fā)人員、框架,甚至是基本方式。

    在這篇文章中,我將帶您探究 JavaScript 的一些特性,看看這些特性如何讓它如此具有吸引力:

    • 高階函數(shù): 一個(gè)高階函數(shù)可以將函數(shù)作為參數(shù),也可以返回一個(gè)函數(shù)。此特性讓 JavaScript 程序員可以用 Java 語(yǔ)言所不能提供的方法來(lái)操縱函數(shù)。

    • 動(dòng)態(tài)類(lèi)型:通過(guò)延遲綁定,JavaScript 可以更準(zhǔn)確和更靈活。

    • 靈活的對(duì)象模型:JavaScript 的對(duì)象模型使用一種相對(duì)不常見(jiàn)的方式進(jìn)行繼承 —— 稱(chēng)為原型 —— 而不是 Java 語(yǔ)言中更常見(jiàn)的基于類(lèi)的對(duì)象模型。

    您可能已經(jīng)熟悉動(dòng)態(tài)類(lèi)型模型、高階函數(shù)形式的函數(shù)式編程以及開(kāi)放對(duì)象模型這些概念,因?yàn)槲以谄渌?i>跨越邊界 系列文章中已經(jīng)作過(guò)相關(guān)的介紹。如果您從未進(jìn)行過(guò)任何正式的 JavaScript 開(kāi)發(fā),您很可能會(huì)認(rèn)為這些特性屬于非常復(fù)雜的語(yǔ)言,例如 Python、Lisp、Smalltalk 和 Haskell,而絕非像 JavaScript 這樣的語(yǔ)言所能提供的。因此,我將用實(shí)際的代碼示例來(lái)說(shuō)明這些概念。

    立即開(kāi)始

    您無(wú)需設(shè)置 JavaScript。如果您可以在瀏覽器中閱讀此篇文章,就證明您已經(jīng)準(zhǔn)備就緒了。本文包含的所有編程示例都可以在大多數(shù)瀏覽器內(nèi)運(yùn)行。我使用的是 Firefox。

    用在 <script type='text/javascript'></script> 標(biāo)記之間所包含的 JavaScript 加載簡(jiǎn)單的 Web 頁(yè)面。清單 1 可以顯示 Hello, World 文本:



    清單 1. Hello, world
    				
    <script type='text/javascript'>
    alert('Hello, World.')
    </script>
    

    要運(yùn)行此代碼,只需創(chuàng)建一個(gè)名為 example1.html 的文件。將清單 1 的代碼復(fù)制到該文件內(nèi),并在瀏覽器中加載此文件(參看 下載 部分以獲得本文使用的所有示例 HTML 文件)。注意到每次重載此頁(yè)面時(shí),該代碼都會(huì)立即執(zhí)行。

    alert 是個(gè)函數(shù)調(diào)用,只有一個(gè)字符串作為參數(shù)。圖 1 顯示了由清單 1 中的代碼彈出的警告框,顯示文本 “Hello, World”。如果代碼在 HTML body 之內(nèi)(目前并未指定任何 body,但瀏覽器能接受不規(guī)則的 HTML,并且整個(gè)頁(yè)面都默然作為一個(gè) body 被處理)。頁(yè)面一旦加載,JavaScript 就會(huì)立即執(zhí)行。



    圖 1. Hello, world
    Hello, World.

    如果要延遲執(zhí)行,可以在 HTML <head> 元素聲明 JavaScript 函數(shù),如清單 2 所示:



    清單 2. 延遲執(zhí)行
    				
    <head>
        
        <script type='text/javascript'>
            function hello() {
                alert('Hello, World.')
            }
        </script>
    </head>
    <body>
        <button onclick="hello();">Say Hello</button>
    </body>
    

    將清單 2 中的代碼輸入到一個(gè) HTML 文件,在瀏覽器內(nèi)加載該文件,單擊 Say Hello 按鈕,結(jié)果如圖 2 所示:



    圖 2. 延遲執(zhí)行
    延遲執(zhí)行




    回頁(yè)首


    高階函數(shù)

    清單 2,可以大致體會(huì)到一些 JavaScript 在操縱函數(shù)方面的能力。將函數(shù)名稱(chēng)傳遞給 HTML button 標(biāo)記并利用 HTML 的內(nèi)置事件模型。使用 JavaScript 時(shí),我會(huì)經(jīng)常在變量或數(shù)組中存儲(chǔ)函數(shù)(在本文后面的 對(duì)象模型 一節(jié),您會(huì)看到 JavaScript 對(duì)象模型策略大量使用了此技巧)。例如,查看一下清單 3:



    清單 3. 用變量操縱函數(shù)
    				
    <head>
        
        <script type='text/javascript'>
            hot = function hot() {
                alert('Sweat.')
            }
            cold  = function cold() {
                alert('Shiver.')
            }
            
            function swap() {
                temp = hot
                hot = cold
                cold = temp    
                alert('Swapped.')
            }
        </script>
    </head>
    <body>
        <button onclick="hot();">Hot</button>
        <button onclick="cold();">Cold</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    函數(shù)是 JavaScript 中的一類(lèi)對(duì)象,可以自由地操縱它們。首先我聲明兩個(gè)函數(shù):hotcold。并分別在不同的變量存儲(chǔ)它們。單擊 Hot 或 Cold 按鈕會(huì)調(diào)用對(duì)應(yīng)的函數(shù),生成一個(gè)告警。接下來(lái),聲明另一個(gè)函數(shù)用來(lái)交換 Hot 和 Cold 按鈕的值,將此函數(shù)與第三個(gè)按鈕關(guān)聯(lián),該按鈕顯示如圖 3 所示的告警:



    圖 3. 操縱函數(shù)

    這個(gè)例子說(shuō)明可以像處理其他變量一樣處理函數(shù)。C 開(kāi)發(fā)人員很容易將此概念看作是函數(shù)指針 功能,但 JavaScript 的高階函數(shù)的功能更為強(qiáng)大。該特性讓 JavaScript 程序員能夠像處理其他變量類(lèi)型一樣輕松處理動(dòng)作或函數(shù)。

    將函數(shù)用作函數(shù)的參數(shù),或?qū)⒑瘮?shù)作為值返回,這些概念屬于高階函數(shù)的領(lǐng)域。清單 4 對(duì) 清單 3 做了一點(diǎn)點(diǎn)修改,顯示了能返回函數(shù)的高階函數(shù):



    清單 4. 高階函數(shù)
    				
    <head>
    
        <script type='text/javascript'>
    
            function temperature() {
                return current
            }
    
            hot = function hot() {
                alert('Hot.')
            }
    
            cold  = function cold() {
                alert('Cold.')
            }
    
            current = hot
    
            function swap() {
                if(current == hot) {
                  current = cold
                } else {
                  current = hot
                }
            }
        </script>
    </head>
    <body>
        <button onclick="funct = temperature()();">Temperature</button>
        <button onclick="swap();">Swap</button>
    </body>
    

    這個(gè)例子解決了一個(gè)常見(jiàn)問(wèn)題:如何將更改中的行為附加到用戶(hù)接口事件?通過(guò)高階函數(shù),這很容易做到。temperature 高階函數(shù)返回 current 的值,而 current 又可以有 hotcold 函數(shù)。看一下這個(gè)有些陳舊的函數(shù)調(diào)用:temperature()()。第一組括號(hào)用于調(diào)用 temperature 函數(shù)。第二組括號(hào)調(diào)用由 temperature返回 的函數(shù)。圖 4 顯示了輸出:



    圖 4. 高階函數(shù)
    高階函數(shù)

    高階函數(shù)是函數(shù)式編程的基礎(chǔ),對(duì)比面向?qū)ο缶幊蹋瘮?shù)式編程代表了更高級(jí)別的抽象。但 JavaScript 的實(shí)力并不僅限于高階函數(shù)。JavaScript 的動(dòng)態(tài)類(lèi)型就極為適合 UI 開(kāi)發(fā)。





    回頁(yè)首


    動(dòng)態(tài)類(lèi)型

    通過(guò)靜態(tài)類(lèi)型,編譯器可以檢查參數(shù)和變量的值或針對(duì)一個(gè)給定操作所允許的返回值。其優(yōu)勢(shì)是編譯器可以做額外的錯(cuò)誤檢查。而且靜態(tài)類(lèi)型還可以為諸如 IDE 這樣的工具提供更多信息,帶來(lái)其他一些特性,比如更好的代碼完成功能。但靜態(tài)類(lèi)型也存在著如下一些劣勢(shì):

    • 必須提前聲明意圖,這常常會(huì)導(dǎo)致靈活性降低。例如,更改一個(gè) Java 類(lèi)就會(huì)更改類(lèi)的類(lèi)型,因而必須重新編譯。對(duì)比之下,Ruby 允許開(kāi)放的類(lèi),但更改一個(gè) Java 類(lèi)還是會(huì)更改類(lèi)的類(lèi)型。

    • 要實(shí)現(xiàn)相同的功能,必須輸入更多的代碼。例如,必須用參數(shù)形式包括進(jìn)類(lèi)型信息,必須用函數(shù)形式返回值和所有變量的類(lèi)型。另外,還必須聲明所有變量并顯式地轉(zhuǎn)化類(lèi)型。

    • 靜態(tài)語(yǔ)言的編譯-部署周期要比動(dòng)態(tài)語(yǔ)言的部署周期長(zhǎng),盡管一些工具可被用來(lái)在某種程度上緩解這一問(wèn)題。

    靜態(tài)類(lèi)型更適合用于構(gòu)建中間件或操作系統(tǒng)的語(yǔ)言中。UI 開(kāi)發(fā)常常需要更高的效率和靈活性,所以更適合采用動(dòng)態(tài)類(lèi)型。我深知這種做法存在危險(xiǎn)。相信使用過(guò) JavaScript 的 Web 開(kāi)發(fā)人員都曾經(jīng)為編譯器本應(yīng)檢測(cè)到的錯(cuò)誤類(lèi)型的變量而絞盡腦汁。但它所帶來(lái)的優(yōu)勢(shì)同樣不可否認(rèn)。下面將舉例加以說(shuō)明。

    首先,考慮一個(gè)對(duì)象的情況。在清單 5 中,創(chuàng)建一個(gè)新對(duì)象,并訪(fǎng)問(wèn)一個(gè)不存在的屬性,名為 color



    清單 5. 引入一個(gè)屬性
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = 'blue'
        alert('The color is ' + blank_object.color)
    </script>
    

    當(dāng)加載并執(zhí)行此應(yīng)用程序時(shí),會(huì)得到如圖 5 所示的結(jié)果:



    圖 5. 引入屬性
     引入屬性

    JavaScript 并不會(huì)報(bào)告 blue 屬性不存在的錯(cuò)誤。靜態(tài)類(lèi)型的擁護(hù)者大都會(huì)被本例所嚇倒,因?yàn)楸纠械腻e(cuò)誤被很好地隱匿了。雖然這種做法多少會(huì)讓您感覺(jué)有些不正當(dāng),但您也不能否認(rèn)它巨大的誘惑力。您可以很快引入屬性。如果將本例和本文之前的例子結(jié)合起來(lái),還可以引入行為。記住,變量可以保存函數(shù)!所以,基于動(dòng)態(tài)類(lèi)型和高階函數(shù),您可以在任何時(shí)候向類(lèi)中引入任意的行為。

    可以輕松地重寫(xiě) 清單 5,使其如清單 6 所示:



    清單 6. 引入行為
    				
    <script type='text/javascript'>
        blank_object = new Object();
        blank_object.color = function() { return 'blue'}
        alert('The color is ' + blank_object.color())
    </script>
    

    從上例可以看出,在 JavaScript 的不同概念之間可以如此輕松地來(lái)回變換,其含義上的變化很大 —— 比如,是引入行為還是引入數(shù)據(jù) —— 但語(yǔ)法上的變化卻很小。該語(yǔ)言很好的延展性是它的一種優(yōu)勢(shì),但同樣也是其缺點(diǎn)所在。實(shí)際上,該語(yǔ)言本身的對(duì)象模型就是 JavaScript 延展程度的一種體現(xiàn)。





    回頁(yè)首


    對(duì)象模型

    到目前為止,您應(yīng)該對(duì) JavaScript 有一個(gè)正確的評(píng)價(jià)了,它絕非只如一個(gè)玩具那么簡(jiǎn)單。事實(shí)上,很多人都使用過(guò)其對(duì)象模型創(chuàng)建過(guò)極為復(fù)雜、設(shè)計(jì)良好的面向?qū)ο筌浖5珜?duì)象模型尤其是用于繼承的對(duì)象模型又非您一貫認(rèn)為的那樣。

    Java 語(yǔ)言是基于類(lèi)的。當(dāng)構(gòu)建應(yīng)用程序時(shí),也同時(shí)構(gòu)建了可以作為所有對(duì)象的模板的新類(lèi)。然后調(diào)用 new 來(lái)實(shí)例化該模板,創(chuàng)建一個(gè)新對(duì)象。而在 JavaScript 中,所創(chuàng)建的是一個(gè)原型,此原型是一個(gè)實(shí)例,可以創(chuàng)建所有未來(lái)的對(duì)象。

    現(xiàn)在先暫且放下這些抽象的概念,去查看一些實(shí)際代碼。比如,清單 7 創(chuàng)建了一個(gè)簡(jiǎn)單的 Animal,它具有 name 屬性和 speak 動(dòng)作。其他動(dòng)物會(huì)從這個(gè)基礎(chǔ)繼承。



    清單 7. 創(chuàng)建一個(gè)構(gòu)造函數(shù)
    				
    <script type='text/javascript'>        
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    
    myAnimal = new Animal();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
    
    </script>
    

    清單 7 的結(jié)果如圖 6 所示:



    圖 6. 創(chuàng)建一個(gè)構(gòu)造函數(shù)
    構(gòu)造函數(shù)

    對(duì)于 Java 開(kāi)發(fā)人員而言,清單 7 中的代碼看起來(lái)多少有點(diǎn)生疏和奇怪。實(shí)際上對(duì)于沒(méi)有親自構(gòu)建過(guò)對(duì)象的許多 JavaScript 開(kāi)發(fā)人員來(lái)說(shuō),這些代碼同樣看起來(lái)有點(diǎn)生疏和奇怪。也許,下面的解釋可以讓大家能夠更好地理解這段代碼。

    實(shí)際上,您只需重點(diǎn)關(guān)注其中三段信息。首先,JavaScript 用嵌套函數(shù)表示對(duì)象。這意味著清單 7 中的 Animal 的定義是一種有效的語(yǔ)法。第二,JavaScript 基于原型或現(xiàn)有的對(duì)象的實(shí)例來(lái)構(gòu)造對(duì)象,而非基于類(lèi)模板。funct() 是一種調(diào)用,但 new Animal() 卻基于 Animal 內(nèi)的原型構(gòu)造一個(gè)對(duì)象。最后,在 JavaScript 中,對(duì)象只是函數(shù)和變量的集合。每個(gè)對(duì)象并不與類(lèi)型相關(guān),所以可以自由地修改這種結(jié)構(gòu)。

    回到 清單 7。如您所見(jiàn),JavaScript 基于在 Animal 中指定的原型定義一個(gè)新對(duì)象:myAnimal。繼而可以使用原型中的屬性和函數(shù),甚或重定義函數(shù)和屬性。這種靈活性可能會(huì)讓 Java 開(kāi)發(fā)人員受不了,因?yàn)樗麄儾涣?xí)慣這種行為,但它的確是一種十分強(qiáng)大的模型。

    現(xiàn)在我還要更深入一步。您還可以使用名為 prototype 實(shí)例變量來(lái)指定對(duì)象的基礎(chǔ)。方法是設(shè)置 prototype 實(shí)例變量使其指向繼承鏈的父。如此設(shè)置 prototype 之后,您所創(chuàng)建的對(duì)象會(huì)為未指定的那些對(duì)象繼承屬性和函數(shù)。這樣一來(lái),您就可以模仿面向?qū)ο蟮睦^承概念。以清單 8 為例:



    清單 8. 通過(guò)原型繼承
    				
    <script type='text/javascript'>        
    
    Animal = function() {
        this.name = "nobody"
        this.speak = function () {
            return "Who am I?"
        }
    }
    Dog = function() {
      this.speak = function() {
        return "Woof!"
      }
    }
    Dog.prototype = new Animal();
    
    myAnimal = new Dog();
    alert('The animal named ' + myAnimal.name + 
          ' says ' + myAnimal.speak());
          </script>
    

    在清單 8 中,創(chuàng)建了一個(gè) Dog 原型。此原型基于 AnimalDog 重定義 speak() 方法但卻不會(huì)對(duì) name() 方法做任何改動(dòng)。隨后,將原型 Dog 設(shè)置成 Animal。圖 7 顯示了其結(jié)果:



    圖 7. 通過(guò)原型繼承
    繼承

    這也展示了 JavaScript 是如何解決到屬性或方法的引用問(wèn)題的:

    • JavaScript 基于原始的原型創(chuàng)建實(shí)例,該原型在構(gòu)造函數(shù)中定義。任何對(duì)方法或?qū)傩缘囊枚紩?huì)使用所生成的原始副本。

    • 您可以在對(duì)象內(nèi)像定義其他任何變量一樣重新定義這些變量。這樣做必然會(huì)更改此對(duì)象。所以您顯式定義的任何屬性或函數(shù)都將比在原始的原型中定義的那些屬性或函數(shù)優(yōu)先級(jí)要高。

    • 如果您顯式設(shè)置了名為 prototype 的實(shí)例變量,JavaScript 就會(huì)在此實(shí)例中尋找任何未定義的實(shí)例變量或?qū)傩浴_@種查找是遞歸的:如果 在 prototype 內(nèi)定義的實(shí)例不能找到屬性或函數(shù),它就會(huì)在 原型中查找,依此類(lèi)推。

    那么,JavaScript 的繼承模型到底是什么樣的?這取決于您如何對(duì)它進(jìn)行定義。您需要定義繼承行為以便可以覆蓋它。然而,從本質(zhì)上講,JavaScript 更像是一種函數(shù)式語(yǔ)言,而非面向?qū)ο蟮恼Z(yǔ)言,它使用一些智能的語(yǔ)法和語(yǔ)義來(lái)仿真高度復(fù)雜的行為。其對(duì)象模型極為靈活、開(kāi)放和強(qiáng)大,具有全部的反射性。有些人可能會(huì)說(shuō)它太過(guò)靈活。而我的忠告則是,按具體作業(yè)的需要選擇合適的工具。





    回頁(yè)首


    結(jié)束語(yǔ)

    JavaScript 對(duì)象模型構(gòu)建在該語(yǔ)言的其他功能之上來(lái)支持大量的庫(kù),比如 Dojo(參見(jiàn) 參考資料)。這種靈活性讓每個(gè)框架能夠以一種精細(xì)的方式更改對(duì)象模型。在某種程度上,這種靈活性是一種極大的缺點(diǎn)。它可以導(dǎo)致可怕的互操作性問(wèn)題(盡管該語(yǔ)言的靈活性可以部分緩解這些問(wèn)題)。

    而另一方面,靈活性又是一種巨大的優(yōu)勢(shì)。Java 語(yǔ)言一直苦于無(wú)法充分增強(qiáng)其靈活性,原因是它的基本對(duì)象模型還未靈活到可以被擴(kuò)展的程度。一個(gè)典型的企業(yè)級(jí)開(kāi)發(fā)人員為能夠成功使用 Java 語(yǔ)言必須要學(xué)習(xí)很多東西,而新出現(xiàn)的一些優(yōu)秀的開(kāi)放源碼項(xiàng)目和新技術(shù),比如面向方面編程、Spring 編程框架和字節(jié)碼增強(qiáng)庫(kù),則帶來(lái)了大量要學(xué)的代碼。

    最后,JavaScript 優(yōu)秀的靈活性的確讓您體會(huì)到了一些高階語(yǔ)言的強(qiáng)大功能。當(dāng)然您無(wú)需選擇為每個(gè)項(xiàng)目或大多數(shù)項(xiàng)目都做這樣的權(quán)衡和折衷。但了解一種語(yǔ)言的優(yōu)勢(shì)和劣勢(shì) —— 通過(guò)參考大量信息,而不僅僅基于廣告宣傳或公眾意見(jiàn) —— 會(huì)讓您可以更好地控制何時(shí)需要使用以及何時(shí)不能使用這種語(yǔ)言。當(dāng)您在修改 JavaScript Web 小部件時(shí),您至少知道該如何讓此語(yǔ)言發(fā)揮它最大的優(yōu)勢(shì)。請(qǐng)繼續(xù)跨越邊界吧。


    參考資料

    學(xué)習(xí)
    posted @ 2007-01-21 15:49 海思 閱讀(241) | 評(píng)論 (0)編輯 收藏

    主站蜘蛛池模板: 久久精品亚洲乱码伦伦中文| 亚洲午夜福利精品无码| 亚洲中文字幕一二三四区苍井空| 97碰公开在线观看免费视频| 亚洲精品免费网站| 国产色婷婷精品免费视频| 男女交性无遮挡免费视频| 久久亚洲国产精品123区| 久久免费观看国产精品88av| 国产精品亚洲片在线va| 国产精品极品美女免费观看| 男女超爽视频免费播放| 国产AV无码专区亚洲精品| 97公开免费视频| 亚洲欧美日韩一区二区三区| 亚洲人成国产精品无码| 成人在线免费视频| 亚洲人成在线影院| 最近的免费中文字幕视频| 一级毛片a免费播放王色电影| 亚洲高清国产AV拍精品青青草原| 日本成年免费网站| 青草青草视频2免费观看| 亚洲产国偷V产偷V自拍色戒| 国产精品视频免费一区二区| 一区二区三区免费视频播放器| 亚洲午夜精品久久久久久人妖| 全免费一级毛片在线播放| 最近2019中文免费字幕在线观看| 亚洲一卡二卡三卡| 亚洲精品乱码久久久久久不卡| 久久久久久夜精品精品免费啦| 亚洲国产午夜精品理论片在线播放| 国产成人精品日本亚洲专区61| 国产成人免费网站| aa级女人大片喷水视频免费| 亚洲中文无码mv| 亚洲AV日韩精品久久久久久 | 亚洲不卡中文字幕无码| 91av视频免费在线观看| 国产精品日本亚洲777|