新版類和對象培訓(xùn)課件_第1頁
新版類和對象培訓(xùn)課件_第2頁
新版類和對象培訓(xùn)課件_第3頁
新版類和對象培訓(xùn)課件_第4頁
新版類和對象培訓(xùn)課件_第5頁
已閱讀5頁,還剩183頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

類和對象ClassandObject精選類和對象ClassandObject精選關(guān)于對象式語言精選本課程并不系統(tǒng)講授Eiffel語言但應(yīng)學(xué)會“欣賞”Eiffel語言(比較“純”)它首先是一個對象式程序設(shè)計(jì)語言但強(qiáng)調(diào)從分析到設(shè)計(jì)到實(shí)現(xiàn)的平滑過渡2關(guān)于對象式語言精選本課程并不系統(tǒng)講授Eiffel語言2摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來3摘要精選三個世界:面向?qū)ο蟮慕?摘要三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來精選4摘要三個世界:面向?qū)ο蟮慕>x4三個世界精選客觀世界DVD播放機(jī)Whatisreality?復(fù)雜性認(rèn)識的主觀性問題世界抽象!AmodelofasubsetoftherealityDVD播放機(jī)計(jì)算機(jī)(軟件)世界Amodelofamodelofasubsetofthereality5三個世界精選客觀世界DVD播放機(jī)2022/12/1InstituteofComputerSoftwareNanjingUniversity現(xiàn)實(shí)世界問題世界軟件世界Reality抽象精選62022/11/30InstituteofCompute摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來7摘要精選三個世界:面向?qū)ο蟮慕?面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance8面向?qū)ο笤瓌t精選ObjectOrientationEnca面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance9面向?qū)ο笤瓌t精選ObjectOrientationEnca回顧:抽象數(shù)據(jù)類型精選抽象數(shù)據(jù)類型(ADT):用數(shù)學(xué)方法定義對象集合和運(yùn)算集合,僅通過運(yùn)算的性質(zhì)刻畫數(shù)據(jù)對象,而獨(dú)立于計(jì)算機(jī)中可能的表示方法ADT規(guī)約方法代數(shù)規(guī)范語法部分,公理部分ADT實(shí)現(xiàn)E1,E2,E310回顧:抽象數(shù)據(jù)類型精選抽象數(shù)據(jù)類型(ADT):用數(shù)學(xué)方法定義面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance11面向?qū)ο笤瓌t精選ObjectOrientationEnca封裝精選封裝是把過程和數(shù)據(jù)包圍起來,對數(shù)據(jù)的訪問只能通過已定義的界面。DVD播放機(jī)12封裝精選封裝是把過程和數(shù)據(jù)包圍起來,對數(shù)據(jù)的訪問只能通過已定精選封裝ProfessorClarkneedstobeabletoteachfourclassesinthenextsemester.SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()ProfessorClarkSetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:4SetMaxLoad(4)13精選封裝ProfessorClarkneedstob精選封裝—信息/實(shí)現(xiàn)隱藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number

Deposit(){…}Withdraw(){…}Transfer(){…}14精選封裝—信息/實(shí)現(xiàn)隱藏InterfaceClientDep精選封裝封裝使得對象在抽象所界定的范圍內(nèi)保持相對的獨(dú)立,從而保證對象設(shè)計(jì)和對象實(shí)施方法的可靠分離?!O(shè)計(jì)者和使用者分離!封裝可以防止由于程序模塊之間的互相依賴性而導(dǎo)致程序“不穩(wěn)定”——不會因某個部分的修改而導(dǎo)致整個系統(tǒng)許多部分都發(fā)生改動。封裝是相對的!不能也沒有必要阻止編程人員去查看實(shí)施細(xì)節(jié)。15精選封裝封裝使得對象在抽象所界定的范圍內(nèi)保持相對的獨(dú)立,從而精選封裝vs.繼承矛盾嗎?No!封裝性主要指的是對象的封裝性,引入繼承機(jī)制后,對象仍然是封裝地很好的實(shí)體,其它對象與它通信只能發(fā)送消息。相似性:共享代碼!繼承:靜態(tài)共享代碼封裝:動態(tài)共享代碼16精選封裝vs.繼承矛盾嗎?No!16精選模塊化傳統(tǒng)的模塊劃分方法:要求組成的子程序(模塊)有實(shí)際意義和明確的某個功能功能分解和結(jié)構(gòu)分解OO的模塊劃分目標(biāo):生成一組有助于降低系統(tǒng)開發(fā)費(fèi)用的模塊,通過模塊劃分所得到的模塊應(yīng)該能夠保證可以獨(dú)立的生成和修改,每個模塊的結(jié)構(gòu)應(yīng)該足夠簡單17精選模塊化傳統(tǒng)的模塊劃分方法:要求組成的子程序(模塊)有實(shí)際精選模塊化與抽象和封裝密切相關(guān)模塊的劃分是以抽象出來的對象的性質(zhì)和功能為依據(jù)的模塊是封裝得以實(shí)現(xiàn)的技術(shù)保障Booch:“模塊化是反映一個被分解成一組相關(guān)聯(lián)的松散結(jié)合模塊組成系統(tǒng)的一個特性?!蹦K化以模塊為基礎(chǔ)18精選模塊化與抽象和封裝密切相關(guān)18精選模塊與類型的統(tǒng)一模塊是軟件分解的單元,是語法概念類型是某些動態(tài)對象的靜態(tài)描述,是語義概念傳統(tǒng)語言模塊與類型分離對象語言模塊與類型統(tǒng)一類型:類是抽象數(shù)據(jù)類型的實(shí)現(xiàn)模塊:類是對象式程序的基本組成單元基于類的面向?qū)ο蟮恼Z言機(jī)制的強(qiáng)有力之處在于“類”統(tǒng)一了類型和模塊19精選模塊與類型的統(tǒng)一模塊是軟件分解的單元,是語法概念基于類的面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance20面向?qū)ο笤瓌t精選ObjectOrientationEnca精選層次性封裝性幫助隱藏細(xì)節(jié);模塊化使結(jié)構(gòu)更加有序,但仍然不夠!層次性是對抽象的排序和定位類結(jié)構(gòu)關(guān)系(“isa”)對象結(jié)構(gòu)關(guān)系(“partof”)實(shí)現(xiàn)方式繼承:子類,父類單繼承,多繼承聚合:擁有關(guān)系/組合關(guān)系21精選層次性封裝性幫助隱藏細(xì)節(jié);模塊化使結(jié)構(gòu)更加有序,但仍然不精選繼承單繼承CheckingSavingsSuperclass(parent)SubclassesInheritanceRelationshipAncestorDescendents22精選繼承單繼承CheckingSavingsSupercla精選繼承多繼承Usemultipleinheritanceonlywhenneededandalwayswithcaution!MultipleInheritance23精選繼承多繼承Usemultipleinheritanc精選繼承繼承作為模塊擴(kuò)展機(jī)制,體現(xiàn)開閉原則,較好地支持軟件的復(fù)用。繼承作為類型特化機(jī)制,體現(xiàn)分類方法,更合理地支持子類型實(shí)現(xiàn)。繼承也是多態(tài)和動態(tài)綁定機(jī)制的基礎(chǔ)。24精選繼承繼承作為模塊擴(kuò)展機(jī)制,體現(xiàn)開閉原則,較好地支持軟件精選子類對父類的擴(kuò)展與特化繼承表達(dá)的是一種分類演繹的認(rèn)識方法“Toprogramistounderstand.”特化:包含范圍變小,行為特殊化擴(kuò)展:增加新的操作重定義:改變行為25精選子類對父類的擴(kuò)展與特化繼承表達(dá)的是一種分類演繹的認(rèn)識方法精選TheOpen-ClosedPrinciple(OCP)動機(jī):軟件是變化的!開閉原則:“ClosedforModification;OpenforExtension”——對修改關(guān)閉,對擴(kuò)展開放!WhyOCP?--重用HowOCP?--繼承26精選TheOpen-ClosedPrinciple(OTheOpen-ClosedPrincipleModulesshouldbeopenandclosed.Definitions:

Openmodule:Maybeextended.Closedmodule:Usablebyclients.Maybeapproved,baselinedand(ifprogramunit)compiled.Therationalesarecomplementary:

Forclosingamodule(manager’sperspective):Clientsneeditnow.Forkeepingmodulesopen(developer’sperspective):Onefrequentlyoverlooksaspectsoftheproblem.精選27TheOpen-ClosedPrincipleModulTheOpen-ClosedPrinciple(1)精選ACEDB28TheOpen-ClosedPrinciple(1)精TheOpen-ClosedPrinciple(2)精選ACEDBFA’GH

I29TheOpen-ClosedPrinciple(2)精TheOpen-ClosedPrinciple(3)精選ACEDBFA’GH

I30TheOpen-ClosedPrinciple(3)精精選Example31精選Example31面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance32面向?qū)ο笤瓌t精選ObjectOrientationEnca精選多態(tài)多態(tài)性使指相同的操作或函數(shù)、過程可作用于多種類型的對象上并獲得不同的結(jié)果。不同的對象,收到同一消息可以產(chǎn)生不同的結(jié)果,這種現(xiàn)象稱為多態(tài)性。多態(tài)性允許每個對象以適合自身的方式去響應(yīng)共同的消息多態(tài)性增強(qiáng)了軟件的靈活性和重用性。33精選多態(tài)多態(tài)性使指相同的操作或函數(shù)、過程可作用于多種類型的對精選多態(tài)ShapeCircleTriangleSquaredraw()draw()draw()draw()publicclassShapes{publicstaticShaperandShape(){switch((int)(Math.random()*3)){default:case0:returnnewCircle();case1:returnnewSquare();case2:returnnewTriangle();}}publicstaticvoidmain(String[]args){Shape[]s=newShape[3];//向數(shù)組里添加類型

for(inti=0;i<s.length;i++)s[i]=randShape();//用多態(tài)的方法調(diào)用

for(inti=0;i<s.length;i++)s[i].draw();}}

34精選多態(tài)ShapeCircleTriangleSquared精選多態(tài)和動態(tài)綁定通過類繼承機(jī)制實(shí)現(xiàn)子類型,允許子類重定義父類的操作。這樣父類型變量(對象引用)及其上的的操作必然是多態(tài)的。這就在實(shí)現(xiàn)上要求動態(tài)綁定機(jī)制35精選多態(tài)和動態(tài)綁定通過類繼承機(jī)制實(shí)現(xiàn)子類型,允許子類重定義父精選動態(tài)綁定綁定:就是建立methodcall和methodbody(方法本體)的關(guān)聯(lián)。靜態(tài)綁定:指綁定動作發(fā)生于程序執(zhí)行前(由編譯器和連接器完成)。動態(tài)綁定:指綁定動作將在執(zhí)行期間才根據(jù)對象類型而進(jìn)行,不同的對象類型將作出不同的編譯結(jié)果。具有靈活性,但效率有一點(diǎn)損失。找到最合適的methodbody36精選動態(tài)綁定綁定:就是建立methodcall和metho摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來37摘要精選三個世界:面向?qū)ο蟮慕?7類:對象程序靜態(tài)的結(jié)構(gòu)類是對象式軟件系統(tǒng)的基本組成單元類的構(gòu)成類的使用信息隱蔽設(shè)施模塊與類型精選38類:對象程序靜態(tài)的結(jié)構(gòu)類是對象式軟件系統(tǒng)的基本組成單元精選3Class一般說類是抽象數(shù)據(jù)類型的實(shí)現(xiàn)抽象數(shù)據(jù)類型乃是一種規(guī)約;類是OOPL實(shí)現(xiàn)這種類型的設(shè)施;但是Meyer說:“Aclassisanabstractdatatypeequippedwithapossiblypartialimplementation.”Meyer在Eiffel中強(qiáng)調(diào)將ADT規(guī)約作為類的一部分強(qiáng)調(diào)從規(guī)約到實(shí)現(xiàn)的一致表達(dá)和平滑過度類可能只是部分實(shí)現(xiàn)Deferredandeffectiveclass精選39Class一般說類是抽象數(shù)據(jù)類型的實(shí)現(xiàn)精選39Averydeferredclassdeferredclass

COUNTER

Feature

item:INTEGER

isdeferredend

--Countervalue

up

is

--Increaseitemby1. deferred

ensure

item=old

item+1

end

down

is

--Decreaseitemby1. deferred

ensure

item=old

item–1

endinvariant

item>=0end精選40Averydeferredclassdeferred類的構(gòu)成類名繼承關(guān)系成員術(shù)語分類精選41類的構(gòu)成類名精選41AbstractdatatypePOINTx:POINT

REALy:POINT

REAL:POINT

REAL:POINT

REALClassPOINT:Choosearepresentation(polar,cartesian)Inpolarrepresentation,

and

areattributes,

x

and

y

are

routines.精選yx42AbstractdatatypePOINTx:POIAsimpleclassclass

POINT

feature

x,y:REAL

--Pointcartesiancoordinates

move(a,b:REAL)is

--Movebyahorizontallyandbybvertically.

do

x:=x+a y:=y+b end

scale(factor:REAL)is

--Scalebyfactor.

do

x:=factor*

x y:=factor*

y end精選43AsimpleclassclassPOINTfeatClassPOINT(cont’d)distance(p:POINT):REAL

is

--Distancetop

do

Result:=sqrt((x–p.x)^2+(y–p.y)^2) end

ro:REAL

is

--Distancetoorigin(0,0)

do

Result:=sqrt(x^2+y^2) end

theta:REAL

is

--Angletohorizontalaxis

do … endend精選44ClassPOINT(cont’d)distance(術(shù)語Aclassisanimplementationofanabstractdatatype.Instancesoftheclassmaybecreatedatrun-time;theyareobjects.類的實(shí)例在運(yùn)行時刻產(chǎn)生,他們是對象。Everyobjectisaninstanceofaclass.每個對象都是一個類的實(shí)例。Note:InapureO-OlanguagesuchasEiffelandSmalltalkthisistrueevenofbasicobjectssuchasintegersetc.NottrueinC++orJavawheresuchvalueshavespecialstatus.精選45術(shù)語Aclassisanimplementation術(shù)語Aclassischaracterizedbyfeatures.Featurescompriseattributes(representingdatafieldsofinstancesoftheclass)androutines(operationsoninstances).Routinesaresubdividedintoprocedures(effectontheinstance,noresult)andfunctions(result,normallynoeffect).Everyoperation(routineorattributecall)isrelativetoadistinguishedobject,thecurrentinstanceoftheclass.精選46術(shù)語AclassischaracterizedbyFeaturecategoriesbyrole精選CommandQueryFeatureProcedureAttributeFunctionNoresultReturnsresultComputationMemory47Featurecategoriesbyrole精選CoFeaturecategoriesbyimplementation精選ProcedureAttributeFunctionRoutineReturnsresultNoresultMemoryComputationFeature48FeaturecategoriesbyimplemenFeaturecategories精選CommandQueryFeatureProcedureAttributeFunctionNoresultReturnsresultComputationMemoryRoutineReturnsresultNoresultMemoryComputationFeature49Featurecategories精選CommandQueAlternativeterminologyAttributesarealsocalledinstancevariablesordatamember.Routinesarealsocalledmethods,subprograms,orsubroutines.Featurecall—applyingacertainfeatureofaclasstoaninstanceofthatclass—isalsocalledpassingamessagetothatobject.Thenotionoffeatureisparticularlyimportantasitprovidesasingletermtocoverbothattributesandroutines.Itisoftendesirablenottospecifywhetherafeatureisanattributeoraroutine—asexpressedbytheUniformAccessprinciple.精選50AlternativeterminologyAttribu回顧:UniformAccess訪問一致性原則客戶應(yīng)能以實(shí)現(xiàn)無關(guān)的方式訪問模塊的功能,不管這個功能是通過存儲還是計(jì)算來實(shí)現(xiàn)的。Facilitiesmanagedbyamodulemustbeaccessibletoclientsinthesamewaywhetherimplementedbycomputationorstorage.精選51回顧:UniformAccess訪問一致性原則精選51UniformAccessbalance=list_of_deposits.total–list_of_withdrawals.total精選list_of_depositslist_of_withdrawalsbalancelist_of_depositslist_of_withdrawals(A2)(A1)52UniformAccessbalance=list_oUniformaccessthroughfeaturecallToaccessapropertyofapointp1,thenotationisthesameregardlessoftherepresentation,e.g.

p1.x whichisapplicablebothincartesianrepresentation(xisanattribute)andinpolarrepresentation(xisafunctionwithoutarguments).Inthefirstcasethefeaturecallisasimplefieldaccess;intheseconditcausesacomputationtobeperformed.Thereisnodifferenceforclients(exceptpossiblyintermsofperformance).精選53Uniformaccessthroughfeature類的使用類的使用有兩種形式允引(classAisaclientofclassB)繼承(classAisadescendantofclassB)

Clientandsuppliera:SinCFeaturecalla.some_featureora.some_feature(…)orinfixoperatorsSingletargetprinciple精選54類的使用類的使用有兩種形式精選54Useoftheclassinaclient(1/5)class

GRAPHICS

feature

p,q:POINT --Graphicpoints

some_routine

is

--Usepandq.

local

u,v:REAL

do

--Creationinstructions createp createq

endend精選0.00.0p(POINT)0.00.0q(POINT)55Useoftheclassinaclient(Useoftheclassinaclient(2/5)class

GRAPHICS

feature

p,q:POINT --Graphicpoints

some_routine

is

--Usepandq.

local

u,v:REAL

do

--Creationinstructions createp createq

p.move

(4.0,-2.0)

--ComparewithPascal,C,Ada: --Move(p,4.0,-2.0) endend精選4.0-2.0p(POINT)0.00.0q(POINT)56Useoftheclassinaclient(Useoftheclassinaclient(3/5)class

GRAPHICS

feature

p,q:POINT --Graphicpoints

some_routine

is

--Usepandq.

local

u,v:REAL

do

--Creationinstructions createp createq

p.move

(4.0,-2.0)

--ComparewithPascal,C,Ada: --Move(p,4.0,-2.0)

p.scale(0.5) endend精選2.0-1.0p(POINT)0.00.0q(POINT)57Useoftheclassinaclient(Useoftheclassinaclient(4/5)class

GRAPHICS

feature

p,q:POINT --Graphicpoints

some_routine

is

--Usepandq.

local

u,v:REAL

do

--Creationinstructions createp createq

p.move

(4.0,-2.0)

--ComparewithPascal,C,Ada: --Move(p,4.0,-2.0)

p.scale(0.5)

u:=p.distance(q)

v:=p.x

p:=q endend精選2.0-1.0p(POINT)0.00.0q(POINT)58Useoftheclassinaclient(Useoftheclassinaclient(5/5)class

GRAPHICS

feature

p,q:POINT --Graphicpoints

some_routine

is

--Usepandq.

local

u,v:REAL

do

--Creationinstructions createp createq

p.move

(4.0,-2.0)

--ComparewithPascal,C,Ada: --Move(p,4.0,-2.0)

p.scale(0.5)

u:=p.distance(q)

v:=p.x

p:=q

p.scale(-3.0) endend精選2.0-1.0p(POINT)0.00.0q(POINT)59Useoftheclassinaclient(精選模塊與類型的統(tǒng)一從模塊的觀點(diǎn):Setofavailableservices(featuresormethods).從類型的觀點(diǎn):Descriptionofsetofpossiblerun-timeobjects(itsinstances).如何做到?Everyobjectisaninstanceofsomeclass.Connection:Theservicesoftheclass,viewedasamodule,aretheoperationsapplicabletotheinstancesoftheclass,viewedasatype.60精選模塊與類型的統(tǒng)一從模塊的觀點(diǎn):60ApplyingabstractionprinciplesPrivilegesofaclientC

ofaclassAonanattributeattrib:Readaccessifattributeisexported.Assuming a1:A

Thena1.attribisanexpression.精選CAa1:A61ApplyingabstractionprincipleTheprivilegesofaclient精選SecretRead-onlyRead,restrictedwriteFullwrite62Theprivilegesofaclient精選SeApplyingabstractionprinciplesBeyondreadaccess:fullorrestrictedwrite,throughexportedprocedures.Fullwriteprivileges:set_attributeprocedure,e.g.

set_temperature(u:REAL)is

--Set

temperature

valueto

u.

do

temperature:=u

ensure

temperature_set:temperature=u

endClientwillusee.g.x.set_temperature(21.5).精選63ApplyingabstractionprincipleOtherusesofasetterprocedureset_temperature(u:REAL)is

--Set

temperature

valueto

u.

require

not_under_minimum:u

>=-273

not_above_maximum:

u

<=2000 do

temperature:=u

update_database

ensure

temperature_set:temperature=u

end精選64OtherusesofasetterproceduDelphi/C#“properties”Allow

x.temperature:=21.5

ifthereisa“setter”:

private

int

temperature_internal;

public

int

temperature

{

get{return

temperature_internal;}

set{

temperature_internal=value;

//...Otherinstructions;... } }精選65Delphi/C#“properties”Allow精選6Informationhiding精選class

Afeature

f...

g...feature

{NONE}

h...feature

{B,C}

j...feature

{A,B,C} kendInclients,withthedeclarationa1:A,wehave:

a1.f,a1.g:validinanyclient

a1.h:invalidanywhere (includinginA’sowntext).

a1.j:validonlyinB,Candtheirdescendants (notvalidinA!)

a1.k:validinB,Candtheirdescendants, aswellasinAanditsdescendants66Informationhiding精選InclientsInformationhiding(cont’d)Informationhidingonlyappliestousebyclients,usingdotnotationorinfixnotation,aswitha1.f(“Qualifiedcalls”).Unqualifiedcalls(withintheclassitself)arenotsubjecttoinformationhiding:

class

A

feature{NONE}

h

is --Doessomething. do

... end

feature

f

is

--Useh. do

...

h

end

end

精選DVD播放機(jī)67Informationhiding(cont’d)Inf摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來68摘要精選三個世界:面向?qū)ο蟮慕?8對象:系統(tǒng)的運(yùn)行結(jié)構(gòu)對象:Arun-timeinstanceofsomeclass.某對象O是某類C的(直接)實(shí)例O包含為C中定義的屬性(數(shù)據(jù)成員)當(dāng)前狀態(tài) (O的fields)運(yùn)行規(guī)律 類定義的行為面向?qū)ο蟮能浖到y(tǒng)運(yùn)行時由一組對象構(gòu)成。對象是對問題域?qū)ο?,并進(jìn)而對現(xiàn)實(shí)對象的實(shí)現(xiàn),三種對象概念上的一致性與差異性精選DVD播放機(jī)69對象:系統(tǒng)的運(yùn)行結(jié)構(gòu)對象:Arun-timeinstan對象有狀態(tài)Thestateofanobjectisoneofthepossibleconditionsinwhichanobjectmayexist.Thestateofanobjectnormallychangesovertime.精選Name:JClarkEmployeeID:567138DateHired:July25,1991Status:TenuredDiscipline:FinanceMaximumCourseLoad:3classesProfessorClark70對象有狀態(tài)Thestateofanobjectis對象有行為Behaviordetermineshowanobjectactsandreacts.Thevisiblebehaviorofanobjectismodeledbythesetofmessagesitcanrespondto(operationstheobjectcanperform).精選SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()SetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:3ProfessorClark71對象有行為Behaviordetermineshowa對象有標(biāo)識Eachobjecthasauniqueidentity,evenifthestateisidenticaltothatofanotherobject.精選Professor“JClark”teachesBiologyProfessor“JClark”teachesBiology72對象有標(biāo)識Eachobjecthasaunique對象需要合作Objectsareuselessunlesstheycancollaboratetogethertosolveaproblem.Eachobjectisresponsibleforitsownbehaviorandstatus.Nooneobjectcancarryouteveryresponsibilityonitsown.Howdoobjectsinteractwitheachother?Theyinteractthroughmessages.精選73對象需要合作Objectsareuselessunle對象vs.類Aclassisanabstractdefinitionofanobject.Itdefinesthestructureandbehaviorofeachobjectintheclass.ItservesasatemplateforcreatingobjectsObjectsaregroupedintoclasses.Anobjectisaninstanceofaclass.精選ObjectsProfessorSmithProfessorMellonFromRealWorldabstractingClass:ProfessorTocomputerWorldinstancingObjects74對象vs.類Aclassisanabstract摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來75摘要精選三個世界:面向?qū)ο蟮慕?5對象創(chuàng)建對象按需創(chuàng)建,顯式創(chuàng)建。傳統(tǒng)技術(shù)往往基于棧分配實(shí)體運(yùn)行時刻對象動態(tài)結(jié)構(gòu)多變,而難以根據(jù)程序文本預(yù)測Eiffel的對象創(chuàng)建基本創(chuàng)建基本創(chuàng)建+初始化featureCreationprocedures精選76對象創(chuàng)建對象按需創(chuàng)建,顯式創(chuàng)建。精選76CreatinganobjectWiththeclassPOINTasgiven:

my_point:POINT

...

create

my_pointEffectofsuchacreationinstruction:Allocatenewobjectofthetypedeclaredformy_point.Initializeitsfieldstodefaultvalues(0fornumbers,falseforbooleans,nullforcharacters,voidforreferences).Attachittotheinstruction’starget,heremy_point.精選77CreatinganobjectWiththeclaSpecificcreationproceduresclass

POINTcreate

make_cartesian,make_polarfeature--Initialization

make_cartesian(a,b:REAL)is

--Initializetoabscissaa,ordinateb.

do

x:=a

y:=b

end

make_polar...feature

...Therestasbefore...精選78SpecificcreationproceduresclIfthereisacreationclauseCreationinstructionsmustbe“creationcalls”,suchas

create

my_point.make_polar(1,Pi

/

2)精選79IfthereisacreationclauseCIfthereisnocreationclauseAnabsentcreationclause,asin class

POINT --Nocreationclause feature

…Therestasbefore… end isunderstoodasonethatwouldonlylistdefault_create,asifithadbeenwritten class

POINT

create

default_create feature

…Therestasbefore… endProceduredefault_createisdefinedinANYasdoingnothing;anyclasscanredefineittoprovideproperdefaultinitializations.精選80IfthereisnocreationclauseAssociatedconventionThenotation

create

x

isunderstood(ifpermitted)asanabbreviationfor

create

x.default_create精選81AssociatedconventionThenotatToallowbothformsTomakebothformsvalid:

create

my_point aswellas

create

my_point.make_polar(1,Pi

/

2) itsufficestomakedefault_create(redefinedornot)oneofthecreationprocedures:

class

POINT create

make_cartesian,make_polar,default_create feature

...Therestasbefore...精選82ToallowbothformsTomakebotToprohibitinstantiatingaclass

class

NOT_CREATABLE create --Nothinghere! feature

...Therestasbefore... end精選83Toprohibitinstantiatingacl摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來84摘要精選三個世界:面向?qū)ο蟮慕?4對象引用回顧C(jī)++和Java的相應(yīng)機(jī)制VoidReference,clone,copyandcompare對象引用的問題精選85對象引用回顧C(jī)++和Java的相應(yīng)機(jī)制精選85FormsofassignmentandcopyReferenceassignment(aandbofreferencetypes):

b:=a

Objectduplication(shallow):

c:=clone(a)

Objectduplication(deep):

d:=deep_clone(a)

Also:shallowfield-by-fieldcopy(nonewobjectiscreated):

e.copy(a)精選86FormsofassignmentandcopyReShallowanddeepcloningInitialsituation:Resultof:b:=ac:=clone(a)d:=deep_clone(a)“Almaviva”namelandlordloved_oneaO1“Figaro”O(jiān)2“Susanna”O(jiān)3b“Almaviva”O(jiān)4c“Almaviva”namelandlordloved_oneO5“Figaro”O(jiān)6“Susanna”O(jiān)7d精選87ShallowanddeepcloningInitia精選Anobjectisamachine88精選Anobjectisamachine88精選Abastractedobjectbeforeafteritemindexput_rightstartforthModel:Price:Manufacture:Size:89精選Abastractedobjectbeforeafte精選Anobjecthasaninterfacebeforeafteritemindexput_rightstartforth90精選Anobjecthasaninterfacebe精選Anobjecthasanimplementationstartforthput_rightbeforeafteritemindex91精選Anobjecthasanimplementat精選Informationhiddingstartforthput_rightbeforeafteritemindex92精選Informationhiddingstartfort小結(jié)三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來精選93小結(jié)三個世界:面向?qū)ο蟮慕>x93作業(yè)(本次作業(yè)不用提交)嘗試學(xué)習(xí)用Eiffel語言寫一些簡單的面向?qū)ο蟪绦???蓮?下載EiffelStudio亦可簡單一些http://smarteiffel.loria.fr/精選94作業(yè)(本次作業(yè)不用提交)嘗試學(xué)習(xí)用Eiffel語言寫一些簡單類和對象ClassandObject精選類和對象ClassandObject精選關(guān)于對象式語言精選本課程并不系統(tǒng)講授Eiffel語言但應(yīng)學(xué)會“欣賞”Eiffel語言(比較“純”)它首先是一個對象式程序設(shè)計(jì)語言但強(qiáng)調(diào)從分析到設(shè)計(jì)到實(shí)現(xiàn)的平滑過渡96關(guān)于對象式語言精選本課程并不系統(tǒng)講授Eiffel語言2摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來97摘要精選三個世界:面向?qū)ο蟮慕?摘要三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來精選98摘要三個世界:面向?qū)ο蟮慕>x4三個世界精選客觀世界DVD播放機(jī)Whatisreality?復(fù)雜性認(rèn)識的主觀性問題世界抽象!AmodelofasubsetoftherealityDVD播放機(jī)計(jì)算機(jī)(軟件)世界Amodelofamodelofasubsetofthereality99三個世界精選客觀世界DVD播放機(jī)2022/12/1InstituteofComputerSoftwareNanjingUniversity現(xiàn)實(shí)世界問題世界軟件世界Reality抽象精選1002022/11/30InstituteofCompute摘要精選三個世界:面向?qū)ο蟮慕C嫦驅(qū)ο笤瓌t類:對象程序靜態(tài)的結(jié)構(gòu)對象:運(yùn)行時刻的結(jié)構(gòu)對象創(chuàng)建:從類到對象對象引用:對象串起來101摘要精選三個世界:面向?qū)ο蟮慕?面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance102面向?qū)ο笤瓌t精選ObjectOrientationEnca面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance103面向?qū)ο笤瓌t精選ObjectOrientationEnca回顧:抽象數(shù)據(jù)類型精選抽象數(shù)據(jù)類型(ADT):用數(shù)學(xué)方法定義對象集合和運(yùn)算集合,僅通過運(yùn)算的性質(zhì)刻畫數(shù)據(jù)對象,而獨(dú)立于計(jì)算機(jī)中可能的表示方法ADT規(guī)約方法代數(shù)規(guī)范語法部分,公理部分ADT實(shí)現(xiàn)E1,E2,E3104回顧:抽象數(shù)據(jù)類型精選抽象數(shù)據(jù)類型(ADT):用數(shù)學(xué)方法定義面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance105面向?qū)ο笤瓌t精選ObjectOrientationEnca封裝精選封裝是把過程和數(shù)據(jù)包圍起來,對數(shù)據(jù)的訪問只能通過已定義的界面。DVD播放機(jī)106封裝精選封裝是把過程和數(shù)據(jù)包圍起來,對數(shù)據(jù)的訪問只能通過已定精選封裝ProfessorClarkneedstobeabletoteachfourclassesinthenextsemester.SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()ProfessorClarkSetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:4SetMaxLoad(4)107精選封裝ProfessorClarkneedstob精選封裝—信息/實(shí)現(xiàn)隱藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number

Deposit(){…}Withdraw(){…}Transfer(){…}108精選封裝—信息/實(shí)現(xiàn)隱藏InterfaceClientDep精選封裝封裝使得對象在抽象所界定的范圍內(nèi)保持相對的獨(dú)立,從而保證對象設(shè)計(jì)和對象實(shí)施方法的可靠分離?!O(shè)計(jì)者和使用者分離!封裝可以防止由于程序模塊之間的互相依賴性而導(dǎo)致程序“不穩(wěn)定”——不會因某個部分的修改而導(dǎo)致整個系統(tǒng)許多部分都發(fā)生改動。封裝是相對的!不能也沒有必要阻止編程人員去查看實(shí)施細(xì)節(jié)。109精選封裝封裝使得對象在抽象所界定的范圍內(nèi)保持相對的獨(dú)立,從而精選封裝vs.繼承矛盾嗎?No!封裝性主要指的是對象的封裝性,引入繼承機(jī)制后,對象仍然是封裝地很好的實(shí)體,其它對象與它通信只能發(fā)送消息。相似性:共享代碼!繼承:靜態(tài)共享代碼封裝:動態(tài)共享代碼110精選封裝vs.繼承矛盾嗎?No!16精選模塊化傳統(tǒng)的模塊劃分方法:要求組成的子程序(模塊)有實(shí)際意義和明確的某個功能功能分解和結(jié)構(gòu)分解OO的模塊劃分目標(biāo):生成一組有助于降低系統(tǒng)開發(fā)費(fèi)用的模塊,通過模塊劃分所得到的模塊應(yīng)該能夠保證可以獨(dú)立的生成和修改,每個模塊的結(jié)構(gòu)應(yīng)該足夠簡單111精選模塊化傳統(tǒng)的模塊劃分方法:要求組成的子程序(模塊)有實(shí)際精選模塊化與抽象和封裝密切相關(guān)模塊的劃分是以抽象出來的對象的性質(zhì)和功能為依據(jù)的模塊是封裝得以實(shí)現(xiàn)的技術(shù)保障Booch:“模塊化是反映一個被分解成一組相關(guān)聯(lián)的松散結(jié)合模塊組成系統(tǒng)的一個特性?!蹦K化以模塊為基礎(chǔ)112精選模塊化與抽象和封裝密切相關(guān)18精選模塊與類型的統(tǒng)一模塊是軟件分解的單元,是語法概念類型是某些動態(tài)對象的靜態(tài)描述,是語義概念傳統(tǒng)語言模塊與類型分離對象語言模塊與類型統(tǒng)一類型:類是抽象數(shù)據(jù)類型的實(shí)現(xiàn)模塊:類是對象式程序的基本組成單元基于類的面向?qū)ο蟮恼Z言機(jī)制的強(qiáng)有力之處在于“類”統(tǒng)一了類型和模塊113精選模塊與類型的統(tǒng)一模塊是軟件分解的單元,是語法概念基于類的面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance114面向?qū)ο笤瓌t精選ObjectOrientationEnca精選層次性封裝性幫助隱藏細(xì)節(jié);模塊化使結(jié)構(gòu)更加有序,但仍然不夠!層次性是對抽象的排序和定位類結(jié)構(gòu)關(guān)系(“isa”)對象結(jié)構(gòu)關(guān)系(“partof”)實(shí)現(xiàn)方式繼承:子類,父類單繼承,多繼承聚合:擁有關(guān)系/組合關(guān)系115精選層次性封裝性幫助隱藏細(xì)節(jié);模塊化使結(jié)構(gòu)更加有序,但仍然不精選繼承單繼承CheckingSavingsSuperclass(parent)SubclassesInheritanceRelationshipAncestorDescendents116精選繼承單繼承CheckingSavingsSupercla精選繼承多繼承Usemultipleinheritanceonlywhenneededandalwayswithcaution!MultipleInheritance117精選繼承多繼承Usemultipleinheritanc精選繼承繼承作為模塊擴(kuò)展機(jī)制,體現(xiàn)開閉原則,較好地支持軟件的復(fù)用。繼承作為類型特化機(jī)制,體現(xiàn)分類方法,更合理地支持子類型實(shí)現(xiàn)。繼承也是多態(tài)和動態(tài)綁定機(jī)制的基礎(chǔ)。118精選繼承繼承作為模塊擴(kuò)展機(jī)制,體現(xiàn)開閉原則,較好地支持軟件精選子類對父類的擴(kuò)展與特化繼承表達(dá)的是一種分類演繹的認(rèn)識方法“Toprogramistounderstand.”特化:包含范圍變小,行為特殊化擴(kuò)展:增加新的操作重定義:改變行為119精選子類對父類的擴(kuò)展與特化繼承表達(dá)的是一種分類演繹的認(rèn)識方法精選TheOpen-ClosedPrinciple(OCP)動機(jī):軟件是變化的!開閉原則:“ClosedforModification;OpenforExtension”——對修改關(guān)閉,對擴(kuò)展開放!WhyOCP?--重用HowOCP?--繼承120精選TheOpen-ClosedPrinciple(OTheOpen-ClosedPrincipleModulesshouldbeopenandclosed.Definitions:

Openmodule:Maybeextended.Closedmodule:Usablebyclients.Maybeapproved,baselinedand(ifprogramunit)compiled.Therationalesarecomplementary:

Forclosingamodule(manager’sperspective):Clientsneeditnow.Forkeepingmodulesopen(developer’sperspective):Onefrequentlyoverlooksaspectsoftheproblem.精選121TheOpen-ClosedPrincipleModulTheOpen-ClosedPrinciple(1)精選ACEDB122TheOpen-ClosedPrinciple(1)精TheOpen-ClosedPrinciple(2)精選ACEDBFA’GH

I123TheOpen-ClosedPrinciple(2)精TheOpen-ClosedPrinciple(3)精選ACEDBFA’GH

I124TheOpen-ClosedPrinciple(3)精精選Example125精選Example31面向?qū)ο笤瓌t精選ObjectOrientationEncapsulationAbstractionPolymorphismInheritance126面向?qū)ο笤瓌t精選ObjectOrientationEnca精選多態(tài)多態(tài)性使指相同的操作或函數(shù)、過程可作用于多種類型的對象上并獲得不同的結(jié)果。不同的對象,收到同一消息可以產(chǎn)生不同的結(jié)果,這種現(xiàn)象稱為多態(tài)性。多態(tài)性允許每個對象以適合自身的方式去響應(yīng)共同的消息多態(tài)性增強(qiáng)了軟件的靈活性和重用性。127精選多態(tài)多態(tài)性使指相同的操作或函數(shù)、過程可作用于多種類型的對精選多態(tài)ShapeCircleTriangleSquaredraw()draw()draw()draw()publicclassShapes{publicstaticShaperandShape(){switch((int)(Math.random()*3)){default:case0:returnnewCircle();case1:returnnewSquare();case2:returnnewTriangle();}}publicstaticvoidmain(String[]args){Shape[]s=newShape[3];//向數(shù)組里添加類型

for(inti=0;i<s.length;i++)s[i]=randShape();//用多態(tài)的方法調(diào)用

for(inti=0;i<s.length;i++)s[i].draw();}}

128精選多態(tài)ShapeCircleTriangleSquared精選多態(tài)和動態(tài)綁定通過類繼承機(jī)制實(shí)現(xiàn)子類型,允許子類重定義父類的操作。這樣父類型變量(對象引用)及其上的的操作必然是多態(tài)的。這就在實(shí)現(xiàn)上要求動態(tài)綁定機(jī)制129精選多態(tài)

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論