计算机专业毕业设计论文外文文献中英文翻译_第1页
计算机专业毕业设计论文外文文献中英文翻译_第2页
计算机专业毕业设计论文外文文献中英文翻译_第3页
已阅读5页,还剩15页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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欢迎下载精品文档译文对象的创建和存在时间从技术角度说, OOP

46、(面向对象程序设计)只是涉及抽象的数据类型、继承以及多形性,但另一些问题也可能显得非常重要。本节将就这些问题进行探讨。最重要的问题之一是对象的创建及破坏方式。对象需要的数据位于哪儿,如何控制对象的 “ 存在时间 ”呢?针对这个问题,解决的方案是各异其趣的。C+认为程序的执行效率是最重要的一个问题, 所以它允许程序员作出选择。 为获得最快的运行速度, 存储以及存在时间可在编写程序时决定, 只需将对象放置在堆栈(有时也叫作自动或定域变量) 或者静态存储区域即可。 这样便为存储空间的分配和释放提供了一个优先级。 某些情况下,这种优先级的控制是非常有价值的。然而,我们同时也牺牲了灵活性, 因为在编写程

47、序时, 必须知道对象的准确的数量、存在时间、以及类型。如果要解决的是一个较常规的问题,如计算机辅助设计、仓储管理或者空中交通控制,这一方法就显得太局限了。第二个方法是在一个内存池中动态创建对象, 该内存池亦叫 “堆”或者 “内存堆 ”。若采用这种方式, 除非进入运行期, 否则根本不知道到底需要多少个对象,也不知道它们的存在时间有多长, 以及准确的类型是什么。 这些参数都在程序正式运行时才决定的。 若需一个新对象, 只需在需要它的时候在内存堆里简单地创建它即可。 由于存储空间的管理是运行期间动态进行的, 所以在内存堆里分配存储空间的时间比在堆栈里创建的时间长得多 (在堆栈里创建存储空间一般只需要

48、一个简单的指令,将堆栈指针向下或向下移动即可) 。由于动态创建方法使对象本来就倾向于复杂, 所以查找存储空间以及释放它所需的额外开销不会为对象的创建造成明显的影响。 除此以外,更大的灵活性对于常规编程问题的解决是至关重要的。C+允许我们决定是在写程序时创建对象,还是在运行期间创建,这种控制方法更加灵活。 大家或许认为既然它如此灵活, 那么无论如何都应在内存堆里创建对象,而不是在堆栈中创建。但还要考虑另外一个问题,亦即对象的“ 存在时间 ” 或者 “ 生存时间 ”( Lifetime)。若在堆栈或者静态存储空间里创建一个对象,编译器会判断对象。9欢迎下载精品文档的持续时间有多长, 到时会自动 “

49、 破坏 ” 或者 “ 清除 ”它。程序员可用两种方法来破坏一个对象: 用程序化的方式决定何时破坏对象, 或者利用由运行环境提供的一种 “ 垃圾收集器 ”特性,自动寻找那些不再使用的对象, 并将其清除。当然,垃圾收集器显得方便得多,但要求所有应用程序都必须容忍垃圾收集器的存在,并能默许随垃圾收集带来的额外开销。但这并不符合 C+语言的设计宗旨,所以未能包括到 C+里。但 Java 确实提供了一个垃圾收集器 (Smalltalk 也有这样的设计;尽管 Delphi 默认为没有垃圾收集器,但可选择安装;而 C+亦可使用一些由其他公司开发的垃圾收集产品) 。本节剩下的部分将讨论操纵对象时要考虑的另一些

50、因素。1 集合与继承器针对一个特定问题的解决,如果事先不知道需要多少个对象,或者它们的持续时间有多长, 那么也不知道如何保存那些对象。既然如此,怎样才能知道那些对象要求多少空间呢?事先上根本无法提前知道,除非进入运行期。在面向对象的设计中, 大多数问题的解决办法似乎都有些轻率 只是简单地创建另一种类型的对象。 用于解决特定问题的新型对象容纳了指向其他对象的句柄。当然,也可以用数组来做同样的事情, 那是大多数语言都具有的一种功能。但不能只看到这一点。 这种新对象通常叫作 “集合 ”(亦叫作一个 “容器 ”,但AWT在不同的场合应用了这个术语,所以本书将一直沿用 “集合 ”的称呼。在需要的时候,集合会自动扩充自己, 以便适应我们在其中置入的任何东西。 所以我们事先不必知道要在一个集合里容下多少东西。 只需创建一个集合, 以后的工作让它自己负责好了。幸运的是,设计优良的 OOP语言都配套提供了一系列集合。在 C+中,它们是以 “标准模板库 ”(STL)的形式提供的。 Object Pascal 用自己的 “ 可视组件库

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论