版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡介
1、精品文檔外文資料Object landscapes and lifetimesTechnically,OOPisjustaboutabstractdata typing,inheritance,andpolymorphism, but otherissuescan be at least as important.The remainderof this section will cover these issues.One of themost importantfactorsisthe wayobjects are createdanddestroyed.Where is thedataf
2、oran objectand how is the lifetimeoftheobject controlled? There are different philosophies at work here. C+takes the approach thatcontrolof efficiencyis the most importantissue,so it gives the programmer a choice. For maximum run-time speed, thestorageand lifetimecan be determined whilethe program i
3、sbeing written,by placingtheobjects on thestack(theseare sometimes calledautomaticor scoped variables)orin thestaticstoragearea. Thisplacesa priorityon the speed ofstorage allocationand release, and controlof these canbe very valuable in some situations. However, you sacrifice flexibilitybecause you
4、 must know the exact quantity, lifetime, and type of objectswhile you're writingtheprogram. Ifyou are tryingto solvea more generalproblemsuchascomputer-aideddesign,warehousemanagement,orair-traffic control, this is too restrictive.The second approach is to create objects dynamically in a pool of
5、memory called the heap. In this approach, you don't know until run-timehow many objects you need, what their lifetime is, or what their exacttype is.Those aredeterminedatthespurofthemoment whiletheprogramis running. If you need a new object, you simply make it on the heap atthe point that you ne
6、ed it. Because the storage is managed dynamically,at run-time, theamount of timerequired to allocate storage on the heapis significantly longer than the time to create storage on the stack.(Creatingstorageon the stackisoften a singleassembly instructionto。1歡迎下載精品文檔move the stack pointerdown, and ano
7、therto move itback up.)The dynamicapproach makes the generally logical assumption that objects tend to becomplicated,so the extraoverhead of findingstorageand releasingthatstorage will not have an important impact on the creation of an object.In addition, the greater flexibility is essential to solv
8、e the generalprogramming problem.Java uses the second approach, exclusively . Every time you want tocreate an object, you use the new keyword to build a dynamic instance ofthat object.There'sanotherissue,however,and that'sthe lifetimeof an object.With languages thatallow objectstobe created
9、on thestack,the compilerdetermines how long the object lasts and can automatically destroy it.However, if you create it on the heap the compiler has no knowledge ofitslifetime.In a language likeC+, you must determineprogrammaticallywhen to destroy the object, which can lead to memory leaks if you do
10、ntdo it correctly (and this is a common problem in C+ programs). Javaprovidesafeaturecalledagarbagecollectorthatautomaticallydiscovers when an object is no longer in use and destroys it. A garbagecollectorismuch more convenientbecause itreducesthe number ofissuesthat you must track and the code you
11、must write. More important, thegarbage collector provides a much higher level of insurance against theinsidious problem of memory leaks (which has brought many a C+ projectto its knees).The restof thissectionlooks atadditionalfactorsconcerningobjectlifetimes and landscapes.1 Collections and iterator
12、sIf you don tknow how many objects youre going to need to solve aparticular problem, or how long they will last, you also dontknow howtostorethose objects. Howcan you know how muchspace to create forthose。2歡迎下載精品文檔objects? You can t, since that information isntknown until run-time.Thesolutiontomostp
13、roblemsinobject-orienteddesignseemsflippant: you create another type ofobject. The new type of object thatsolves this particular problem holds references to other objects. Ofcourse, you can do the same thing with an array, which is available inmost languages. But theres more. This new object, genera
14、lly called acontainer(alsocalleda collection,butthe Java libraryuses thattermin a differentsense so thisbook willuse “container”),will expand itselfwhenever necessarytoaccommodateeverythingyou placeinsideit.So youdontneed to know how manyobjects youre going to hold in a container.Just create a conta
15、iner object and let it take care of the details.Fortunately, a good OOP language comes with a set of containers aspart of the package. In C+, its part of the Standard C+ Library andis sometimes called the Standard Template Library (STL). Object Pascalhas containersin itsVisualComponentLibrary(VCL).
16、Smalltalkhas a verycomplete set of containers. Java also has containers in its standardlibrary.Insomelibraries,a genericcontaineris consideredgood enoughfor allneeds,and in others(Java,for example) thelibraryhas differenttypes of containers for different needs: a vector (called an ArrayListin Java)
17、for consistent access to all elements, and a linked list forconsistentinsertionatallelements,forexample,so you can choose theparticulartypethat fitsyourneeds. Containerlibrariesmayalsoincludesets, queues, hash tables, trees, stacks, etc.Allcontainershave someway toput thingsin and get thingsout;ther
18、eare usuallyfunctionstoadd elementstoa container,and otherstofetchthose elements back out. But fetching elements can be more problematic,because a single-selection function is restrictive. What if you want tomanipulate or comparea set ofelements in the containerinstead of justone?。3歡迎下載精品文檔The solut
19、ionisan iterator,which is an objectwhose jobisto selectthe elements within a container and present them to the user of theiterator. As a class, it also provides a level of abstraction. Thisabstractioncan be used toseparatethedetailsofthecontainerfrom thecode that s accessing that container. The cont
20、ainer, via the iterator,is abstractedtobe simplya sequence. The iteratorallowsyou to traversethat sequence without worrying about the underlying structure that is,whether its an ArrayList,a LinkedList,a Stack,orsomethingelse.Thisgives you the flexibilitytoeasilychange theunderlyingdatastructurewitho
21、ut disturbing the code in your program. Java began (in version 1.0and 1.1) with a standard iterator, called Enumeration, for all of itscontainerclasses.Java 2 has added a muchmore completecontainerlibrarythat contains an iterator called Iterator that does more than the olderEnumeration.From a design
22、 standpoint, allyou really wantis a sequencethat canbe manipulatedtosolveyourproblem.Ifasingletypeofsequencesatisfiedallofyour needs,there d be no reason tohave differentkinds.There aretworeasonsthatyouneedachoiceofcontainers.First,containers provide different types of interfaces and external behavi
23、or.A stack has a differentinterfaceand behavior thanthatofa queue, whichis different from that of a set or a list. One of these might provide amore flexiblesolutiontoyourproblem thantheother.Second, differentcontainers have different efficiencies for certain operations. The bestexample isan ArrayLis
24、tand a LinkedList.Both aresimplesequences thatcan haveidenticalinterfacesand externalbehaviors.Butcertainoperationscanhaveradicallydifferentcosts.Randomlyaccessingelements inan ArrayListisa constant-timeoperation;ittakesthesameamount oftimeregardlessofthe elementyouselect.However,in aLinkedList it i
25、s expensive to move through the list to randomly select。4歡迎下載精品文檔an element, and it takes longer to find an element that is further downthe list.On theotherhand,ifyou want toinsertan element in the middleof a sequence, it s much cheaper in a LinkedList than in an ArrayList.These and other operations
26、 have different efficiencies depending on theunderlyingstructureof thesequence. In thedesignphase, you might startwith a LinkedListand, when tuning forperformance,change to an ArrayList.Because of the abstractionvia iterators, you can change from one totheother with minimal impact on your code.In th
27、e end, remember that a container is only a storage cabinet toput objects in. If that cabinet solvesallofyourneeds, it doesnt reallymatter how itisimplemented(a basicconceptwithmost types ofobjects).If youreworkingina programming environment thathas built-inoverheaddue to other factors, then the cost
28、 difference between an ArrayList anda LinkedListmightnot matter.You might need only one type of sequence.You caneven imaginethe“perfect ” containerabstraction,which canautomatically change its underlying implementation according to the wayit is used.2 The singly rooted hierarchyOne of the issues in
29、OOP that has become especially prominent sincethe introduction of C+ is whether all classes should ultimately beinheritedfrom a singlebase class. In Java (as with virtually allotherOOPlanguages)the answer is“yes”and the nameof this ultimatebase classis simply Object. It turns out that the benefits o
30、f the singly rootedhierarchy are many.Allobjectsin a singlyrooted hierarchy have an interfacein common,so they are all ultimately the same type. The alternative (provided byC+) isthat you dontknow that everythingis the same fundamental type.From a backward-compatibilitystandpointthisfits the model o
31、f C betterand can be thought of as lessrestrictive,butwhen you want todo full-on。5歡迎下載精品文檔object-oriented programming you must then build your own hierarchy toprovide the same convenience thats built into other OOP languages. Andin any new class library you acquire, some other incompatible interface
32、will be used. It requires effort (and possibly multiple inheritance) towork the new interface into your design. Is the extra“flexibility”ofC+ worth it? If you need itif you have a large investment in Citsquite valuable.Ifyourestartingfromscratch,otheralternativessuchas Java can often be more product
33、ive.Allobjectsina singlyrootedhierarchy(suchas Java provides) canbe guaranteed to have certain functionality. You know you can performcertainbasic operationson every objectinyoursystem. A singlyrootedhierarchy,along withcreatingallobjectson theheap, greatlysimplifiesargument passing (one of the more
34、 complex topics in C+).A singlyrootedhierarchymakes it much easierto implement a garbagecollector(which isconvenientlybuiltintoJava).The necessarysupportcan be installed in the base class, and the garbage collector can thussend the appropriate messages to every object in the system. Without asinglyr
35、ootedhierarchyandasystemtomanipulatean objectviaareference, it is difficult to implement a garbage collector.Since run-time type information is guaranteed to be in all objects,youll never end up with an object whose type you cannot determine. Thisis especially important with system level operations,
36、 such as exceptionhandling, and to allow greater flexibility in programming.3 Collection libraries and support for easy collection useBecause a container is a tool that youll use frequently, it makessense tohave a libraryofcontainersthatare builtin a reusable fashion,so you can takeone offtheshelfBe
37、cause a containerisa toolthatyoulluse frequently, it makes sense to have a library of containers that arebuilt in a reusable fashion, so you can take one off the shelf and plug。6歡迎下載精品文檔itintoyour program. Java providessuch a library,which shouldsatisfymost needs.Downcasting vs. templates/genericsTo
38、 make these containers reusable, they hold the one universal typeinJava thatwas previouslymentioned:Object.The singlyrooted hierarchymeans thateverythingisan Object,so a containerthatholds Objectscanhold anything. This makes containers easy to reuse.To use such a container,you simply add object refe
39、rencesto it, andlater ask for them back. But,sincethecontainerholdsonlyObjects,whenyou add your objectreference intothecontainer it isupcast to Object,thus losing its identity. When you fetch it back, you get an Objectreference,and nota reference tothetypethatyou put in.So how do youturn it back int
40、o something that has the useful interface of the objectthat you put into the container?Here, the castisused again,butthistimeyourenotcastingup theinheritancehierarchytoa more general type,you castdown the hierarchyto a more specific type. This manner of casting is called downcasting.With upcasting,
41、you know, for example, that a Circle is a type of Shapeso it s safe to upcast, but you dontknow that an Object is necessarilya Circleora Shape so it s hardlysafetodowncast unless you know that swhat you re dealing with.It s not completely dangerous, however, because if you downcast to the wrong thin
42、g you ll get a run-time error called an exception, whichwill be described shortly. When you fetch object references from a container, though, you must have some way to remember exactly what they are so you can perform a proper downcast.Downcasting and the run-timechecks requireextra time forthe runn
43、ing。7歡迎下載精品文檔program, and extra effort from the programmer. Wouldntit make sense tosomehow create the container so that it knows the types that it holds,eliminatingthe need forthe downcast and a possible mistake?The solutionis parameterizedtypes,whichareclassesthatthecompilercanautomaticallycustomiz
44、etowork withparticulartypes.For example,witha parameterized container, the compiler could customize that containerso that it would accept only Shapes and fetch only Shapes.Parameterizedtypesare an importantpart ofC+, partlybecause C+has no singly rooted hierarchy. In C+, the keyword that implementsp
45、arameterized types is“template. ”Java currently has no parameterizedtypes sinceit ispossiblefor itto getby however awkwardly usingthesingly rooted hierarchy. However, a current proposal for parameterized types uses a syntax that is strikingly similar to C+ templates.。8歡迎下載精品文檔譯文對(duì)象的創(chuàng)建和存在時(shí)間從技術(shù)角度說, OOP
46、(面向?qū)ο蟪绦蛟O(shè)計(jì))只是涉及抽象的數(shù)據(jù)類型、繼承以及多形性,但另一些問題也可能顯得非常重要。本節(jié)將就這些問題進(jìn)行探討。最重要的問題之一是對(duì)象的創(chuàng)建及破壞方式。對(duì)象需要的數(shù)據(jù)位于哪兒,如何控制對(duì)象的 “ 存在時(shí)間 ”呢?針對(duì)這個(gè)問題,解決的方案是各異其趣的。C+認(rèn)為程序的執(zhí)行效率是最重要的一個(gè)問題, 所以它允許程序員作出選擇。 為獲得最快的運(yùn)行速度, 存儲(chǔ)以及存在時(shí)間可在編寫程序時(shí)決定, 只需將對(duì)象放置在堆棧(有時(shí)也叫作自動(dòng)或定域變量) 或者靜態(tài)存儲(chǔ)區(qū)域即可。 這樣便為存儲(chǔ)空間的分配和釋放提供了一個(gè)優(yōu)先級(jí)。 某些情況下,這種優(yōu)先級(jí)的控制是非常有價(jià)值的。然而,我們同時(shí)也犧牲了靈活性, 因?yàn)樵诰帉懗?/p>
47、序時(shí), 必須知道對(duì)象的準(zhǔn)確的數(shù)量、存在時(shí)間、以及類型。如果要解決的是一個(gè)較常規(guī)的問題,如計(jì)算機(jī)輔助設(shè)計(jì)、倉儲(chǔ)管理或者空中交通控制,這一方法就顯得太局限了。第二個(gè)方法是在一個(gè)內(nèi)存池中動(dòng)態(tài)創(chuàng)建對(duì)象, 該內(nèi)存池亦叫 “堆”或者 “內(nèi)存堆 ”。若采用這種方式, 除非進(jìn)入運(yùn)行期, 否則根本不知道到底需要多少個(gè)對(duì)象,也不知道它們的存在時(shí)間有多長, 以及準(zhǔn)確的類型是什么。 這些參數(shù)都在程序正式運(yùn)行時(shí)才決定的。 若需一個(gè)新對(duì)象, 只需在需要它的時(shí)候在內(nèi)存堆里簡單地創(chuàng)建它即可。 由于存儲(chǔ)空間的管理是運(yùn)行期間動(dòng)態(tài)進(jìn)行的, 所以在內(nèi)存堆里分配存儲(chǔ)空間的時(shí)間比在堆棧里創(chuàng)建的時(shí)間長得多 (在堆棧里創(chuàng)建存儲(chǔ)空間一般只需要
48、一個(gè)簡單的指令,將堆棧指針向下或向下移動(dòng)即可) 。由于動(dòng)態(tài)創(chuàng)建方法使對(duì)象本來就傾向于復(fù)雜, 所以查找存儲(chǔ)空間以及釋放它所需的額外開銷不會(huì)為對(duì)象的創(chuàng)建造成明顯的影響。 除此以外,更大的靈活性對(duì)于常規(guī)編程問題的解決是至關(guān)重要的。C+允許我們決定是在寫程序時(shí)創(chuàng)建對(duì)象,還是在運(yùn)行期間創(chuàng)建,這種控制方法更加靈活。 大家或許認(rèn)為既然它如此靈活, 那么無論如何都應(yīng)在內(nèi)存堆里創(chuàng)建對(duì)象,而不是在堆棧中創(chuàng)建。但還要考慮另外一個(gè)問題,亦即對(duì)象的“ 存在時(shí)間 ” 或者 “ 生存時(shí)間 ”( Lifetime)。若在堆?;蛘哽o態(tài)存儲(chǔ)空間里創(chuàng)建一個(gè)對(duì)象,編譯器會(huì)判斷對(duì)象。9歡迎下載精品文檔的持續(xù)時(shí)間有多長, 到時(shí)會(huì)自動(dòng) “
49、 破壞 ” 或者 “ 清除 ”它。程序員可用兩種方法來破壞一個(gè)對(duì)象: 用程序化的方式?jīng)Q定何時(shí)破壞對(duì)象, 或者利用由運(yùn)行環(huán)境提供的一種 “ 垃圾收集器 ”特性,自動(dòng)尋找那些不再使用的對(duì)象, 并將其清除。當(dāng)然,垃圾收集器顯得方便得多,但要求所有應(yīng)用程序都必須容忍垃圾收集器的存在,并能默許隨垃圾收集帶來的額外開銷。但這并不符合 C+語言的設(shè)計(jì)宗旨,所以未能包括到 C+里。但 Java 確實(shí)提供了一個(gè)垃圾收集器 (Smalltalk 也有這樣的設(shè)計(jì);盡管 Delphi 默認(rèn)為沒有垃圾收集器,但可選擇安裝;而 C+亦可使用一些由其他公司開發(fā)的垃圾收集產(chǎn)品) 。本節(jié)剩下的部分將討論操縱對(duì)象時(shí)要考慮的另一些
50、因素。1 集合與繼承器針對(duì)一個(gè)特定問題的解決,如果事先不知道需要多少個(gè)對(duì)象,或者它們的持續(xù)時(shí)間有多長, 那么也不知道如何保存那些對(duì)象。既然如此,怎樣才能知道那些對(duì)象要求多少空間呢?事先上根本無法提前知道,除非進(jìn)入運(yùn)行期。在面向?qū)ο蟮脑O(shè)計(jì)中, 大多數(shù)問題的解決辦法似乎都有些輕率 只是簡單地創(chuàng)建另一種類型的對(duì)象。 用于解決特定問題的新型對(duì)象容納了指向其他對(duì)象的句柄。當(dāng)然,也可以用數(shù)組來做同樣的事情, 那是大多數(shù)語言都具有的一種功能。但不能只看到這一點(diǎn)。 這種新對(duì)象通常叫作 “集合 ”(亦叫作一個(gè) “容器 ”,但AWT在不同的場合應(yīng)用了這個(gè)術(shù)語,所以本書將一直沿用 “集合 ”的稱呼。在需要的時(shí)候,集合會(huì)自動(dòng)擴(kuò)充自己, 以便適應(yīng)我們?cè)谄渲兄萌氲娜魏螙|西。 所以我們事先不必知道要在一個(gè)集合里容下多少東西。 只需創(chuàng)建一個(gè)集合, 以后的工作讓它自己負(fù)責(zé)好了。幸運(yùn)的是,設(shè)計(jì)優(yōu)良的 OOP語言都配套提供了一系列集合。在 C+中,它們是以 “標(biāo)準(zhǔn)模板庫 ”(STL)的形式提供的。 Object Pascal 用自己的 “ 可視組件庫
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 2024正式的地區(qū)代理合同范文
- 工程合同功能解析
- 水利工程維修貸款合同
- 2024醫(yī)院藥品供銷合同
- 農(nóng)業(yè)領(lǐng)域合作協(xié)議范本
- 2024年咨詢顧問合作簡單協(xié)議書
- 彩色鋼板工程承包協(xié)議書
- 集裝箱海運(yùn)合同范本
- 2024建筑業(yè)合同范本范文
- 2024個(gè)人房產(chǎn)轉(zhuǎn)讓合同
- 小學(xué)綜合實(shí)踐活動(dòng)-綠色出行教學(xué)課件設(shè)計(jì)
- 防校園欺凌-課件(共28張PPT)
- 第6章 智能網(wǎng)聯(lián)汽車測評(píng)技術(shù)
- 單向板結(jié)構(gòu)設(shè)計(jì)
- 《強(qiáng)化學(xué)習(xí)理論與應(yīng)用》環(huán)境
- 普通高等學(xué)校學(xué)生轉(zhuǎn)學(xué)申請(qǐng)表
- 房租、水、電費(fèi)(專用)收據(jù)Excel模板
- 習(xí)近平總書記關(guān)于教育的重要論述研究學(xué)習(xí)通章節(jié)答案期末考試題庫2023年
- 重癥急性胰腺炎ppt恢復(fù)課件
- 2022江蘇省沿海開發(fā)集團(tuán)限公司招聘23人上岸筆試歷年難、易錯(cuò)點(diǎn)考題附帶參考答案與詳解
- 鄉(xiāng)鎮(zhèn)衛(wèi)生院6S管理內(nèi)容和要求
評(píng)論
0/150
提交評(píng)論