




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
类和对象ClassandObject精选类和对象ClassandObject精选关于对象式语言精选本课程并不系统讲授Eiffel语言但应学会“欣赏”Eiffel语言(比较“纯”)它首先是一个对象式程序设计语言但强调从分析到设计到实现的平滑过渡2关于对象式语言精选本课程并不系统讲授Eiffel语言2摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来3摘要精选三个世界:面向对象的建模3摘要三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来精选4摘要三个世界:面向对象的建模精选4三个世界精选客观世界DVD播放机Whatisreality?复杂性认识的主观性问题世界抽象!AmodelofasubsetoftherealityDVD播放机计算机(软件)世界Amodelofamodelofasubsetofthereality5三个世界精选客观世界DVD播放机2022/12/1InstituteofComputerSoftwareNanjingUniversity现实世界问题世界软件世界Reality抽象精选62022/11/30InstituteofCompute摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来7摘要精选三个世界:面向对象的建模7面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance8面向对象原则精选ObjectOrientationEnca面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance9面向对象原则精选ObjectOrientationEnca回顾:抽象数据类型精选抽象数据类型(ADT):用数学方法定义对象集合和运算集合,仅通过运算的性质刻画数据对象,而独立于计算机中可能的表示方法ADT规约方法代数规范语法部分,公理部分ADT实现E1,E2,E310回顾:抽象数据类型精选抽象数据类型(ADT):用数学方法定义面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance11面向对象原则精选ObjectOrientationEnca封装精选封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。DVD播放机12封装精选封装是把过程和数据包围起来,对数据的访问只能通过已定精选封装ProfessorClarkneedstobeabletoteachfourclassesinthenextsemester.SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()ProfessorClarkSetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:4SetMaxLoad(4)13精选封装ProfessorClarkneedstob精选封装—信息/实现隐藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number
Deposit(){…}Withdraw(){…}Transfer(){…}14精选封装—信息/实现隐藏InterfaceClientDep精选封装封装使得对象在抽象所界定的范围内保持相对的独立,从而保证对象设计和对象实施方法的可靠分离。——设计者和使用者分离!封装可以防止由于程序模块之间的互相依赖性而导致程序“不稳定”——不会因某个部分的修改而导致整个系统许多部分都发生改动。封装是相对的!不能也没有必要阻止编程人员去查看实施细节。15精选封装封装使得对象在抽象所界定的范围内保持相对的独立,从而精选封装vs.继承矛盾吗?No!封装性主要指的是对象的封装性,引入继承机制后,对象仍然是封装地很好的实体,其它对象与它通信只能发送消息。相似性:共享代码!继承:静态共享代码封装:动态共享代码16精选封装vs.继承矛盾吗?No!16精选模块化传统的模块划分方法:要求组成的子程序(模块)有实际意义和明确的某个功能功能分解和结构分解OO的模块划分目标:生成一组有助于降低系统开发费用的模块,通过模块划分所得到的模块应该能够保证可以独立的生成和修改,每个模块的结构应该足够简单17精选模块化传统的模块划分方法:要求组成的子程序(模块)有实际精选模块化与抽象和封装密切相关模块的划分是以抽象出来的对象的性质和功能为依据的模块是封装得以实现的技术保障Booch:“模块化是反映一个被分解成一组相关联的松散结合模块组成系统的一个特性。”模块化以模块为基础18精选模块化与抽象和封装密切相关18精选模块与类型的统一模块是软件分解的单元,是语法概念类型是某些动态对象的静态描述,是语义概念传统语言模块与类型分离对象语言模块与类型统一类型:类是抽象数据类型的实现模块:类是对象式程序的基本组成单元基于类的面向对象的语言机制的强有力之处在于“类”统一了类型和模块19精选模块与类型的统一模块是软件分解的单元,是语法概念基于类的面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance20面向对象原则精选ObjectOrientationEnca精选层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不够!层次性是对抽象的排序和定位类结构关系(“isa”)对象结构关系(“partof”)实现方式继承:子类,父类单继承,多继承聚合:拥有关系/组合关系21精选层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不精选继承单继承CheckingSavingsSuperclass(parent)SubclassesInheritanceRelationshipAncestorDescendents22精选继承单继承CheckingSavingsSupercla精选继承多继承Usemultipleinheritanceonlywhenneededandalwayswithcaution!MultipleInheritance23精选继承多继承Usemultipleinheritanc精选继承继承作为模块扩展机制,体现开闭原则,较好地支持软件的复用。继承作为类型特化机制,体现分类方法,更合理地支持子类型实现。继承也是多态和动态绑定机制的基础。24精选继承继承作为模块扩展机制,体现开闭原则,较好地支持软件精选子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法“Toprogramistounderstand.”特化:包含范围变小,行为特殊化扩展:增加新的操作重定义:改变行为25精选子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法精选TheOpen-ClosedPrinciple(OCP)动机:软件是变化的!开闭原则:“ClosedforModification;OpenforExtension”——对修改关闭,对扩展开放!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面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance32面向对象原则精选ObjectOrientationEnca精选多态多态性使指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。多态性允许每个对象以适合自身的方式去响应共同的消息多态性增强了软件的灵活性和重用性。33精选多态多态性使指相同的操作或函数、过程可作用于多种类型的对精选多态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];//向数组里添加类型
for(inti=0;i<s.length;i++)s[i]=randShape();//用多态的方法调用
for(inti=0;i<s.length;i++)s[i].draw();}}
34精选多态ShapeCircleTriangleSquared精选多态和动态绑定通过类继承机制实现子类型,允许子类重定义父类的操作。这样父类型变量(对象引用)及其上的的操作必然是多态的。这就在实现上要求动态绑定机制35精选多态和动态绑定通过类继承机制实现子类型,允许子类重定义父精选动态绑定绑定:就是建立methodcall和methodbody(方法本体)的关联。静态绑定:指绑定动作发生于程序执行前(由编译器和连接器完成)。动态绑定:指绑定动作将在执行期间才根据对象类型而进行,不同的对象类型将作出不同的编译结果。具有灵活性,但效率有一点损失。找到最合适的methodbody36精选动态绑定绑定:就是建立methodcall和metho摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来37摘要精选三个世界:面向对象的建模37类:对象程序静态的结构类是对象式软件系统的基本组成单元类的构成类的使用信息隐蔽设施模块与类型精选38类:对象程序静态的结构类是对象式软件系统的基本组成单元精选3Class一般说类是抽象数据类型的实现抽象数据类型乃是一种规约;类是OOPL实现这种类型的设施;但是Meyer说:“Aclassisanabstractdatatypeequippedwithapossiblypartialimplementation.”Meyer在Eiffel中强调将ADT规约作为类的一部分强调从规约到实现的一致表达和平滑过度类可能只是部分实现Deferredandeffectiveclass精选39Class一般说类是抽象数据类型的实现精选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类的构成类名继承关系成员术语分类精选41类的构成类名精选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(术语Aclassisanimplementationofanabstractdatatype.Instancesoftheclassmaybecreatedatrun-time;theyareobjects.类的实例在运行时刻产生,他们是对象。Everyobjectisaninstanceofaclass.每个对象都是一个类的实例。Note:InapureO-OlanguagesuchasEiffelandSmalltalkthisistrueevenofbasicobjectssuchasintegersetc.NottrueinC++orJavawheresuchvalueshavespecialstatus.精选45术语Aclassisanimplementation术语Aclassischaracterizedbyfeatures.Featurescompriseattributes(representingdatafieldsofinstancesoftheclass)androutines(operationsoninstances).Routinesaresubdividedintoprocedures(effectontheinstance,noresult)andfunctions(result,normallynoeffect).Everyoperation(routineorattributecall)isrelativetoadistinguishedobject,thecurrentinstanceoftheclass.精选46术语AclassischaracterizedbyFeaturecategoriesbyrole精选CommandQueryFeatureProcedureAttributeFunctionNoresultReturnsresultComputationMemory47Featurecategoriesbyrole精选CoFeaturecategoriesbyimplementation精选ProcedureAttributeFunctionRoutineReturnsresultNoresultMemoryComputationFeature48FeaturecategoriesbyimplemenFeaturecategories精选CommandQueryFeatureProcedureAttributeFunctionNoresultReturnsresultComputationMemoryRoutineReturnsresultNoresultMemoryComputationFeature49Featurecategories精选CommandQueAlternativeterminologyAttributesarealsocalledinstancevariablesordatamember.Routinesarealsocalledmethods,subprograms,orsubroutines.Featurecall—applyingacertainfeatureofaclasstoaninstanceofthatclass—isalsocalledpassingamessagetothatobject.Thenotionoffeatureisparticularlyimportantasitprovidesasingletermtocoverbothattributesandroutines.Itisoftendesirablenottospecifywhetherafeatureisanattributeoraroutine—asexpressedbytheUniformAccessprinciple.精选50AlternativeterminologyAttribu回顾:UniformAccess访问一致性原则客户应能以实现无关的方式访问模块的功能,不管这个功能是通过存储还是计算来实现的。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(精选模块与类型的统一从模块的观点:Setofavailableservices(featuresormethods).从类型的观点:Descriptionofsetofpossiblerun-timeobjects(itsinstances).如何做到?Everyobjectisaninstanceofsomeclass.Connection:Theservicesoftheclass,viewedasamodule,aretheoperationsapplicabletotheinstancesoftheclass,viewedasatype.60精选模块与类型的统一从模块的观点: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播放机67Informationhiding(cont’d)Inf摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来68摘要精选三个世界:面向对象的建模68对象:系统的运行结构对象:Arun-timeinstanceofsomeclass.某对象O是某类C的(直接)实例O包含为C中定义的属性(数据成员)当前状态 (O的fields)运行规律 类定义的行为面向对象的软件系统运行时由一组对象构成。对象是对问题域对象,并进而对现实对象的实现,三种对象概念上的一致性与差异性精选DVD播放机69对象:系统的运行结构对象:Arun-timeinstan对象有状态Thestateofanobjectisoneofthepossibleconditionsinwhichanobjectmayexist.Thestateofanobjectnormallychangesovertime.精选Name:JClarkEmployeeID:567138DateHired:July25,1991Status:TenuredDiscipline:FinanceMaximumCourseLoad:3classesProfessorClark70对象有状态Thestateofanobjectis对象有行为Behaviordetermineshowanobjectactsandreacts.Thevisiblebehaviorofanobjectismodeledbythesetofmessagesitcanrespondto(operationstheobjectcanperform).精选SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()SetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:3ProfessorClark71对象有行为Behaviordetermineshowa对象有标识Eachobjecthasauniqueidentity,evenifthestateisidenticaltothatofanotherobject.精选Professor“JClark”teachesBiologyProfessor“JClark”teachesBiology72对象有标识Eachobjecthasaunique对象需要合作Objectsareuselessunlesstheycancollaboratetogethertosolveaproblem.Eachobjectisresponsibleforitsownbehaviorandstatus.Nooneobjectcancarryouteveryresponsibilityonitsown.Howdoobjectsinteractwitheachother?Theyinteractthroughmessages.精选73对象需要合作Objectsareuselessunle对象vs.类Aclassisanabstractdefinitionofanobject.Itdefinesthestructureandbehaviorofeachobjectintheclass.ItservesasatemplateforcreatingobjectsObjectsaregroupedintoclasses.Anobjectisaninstanceofaclass.精选ObjectsProfessorSmithProfessorMellonFromRealWorldabstractingClass:ProfessorTocomputerWorldinstancingObjects74对象vs.类Aclassisanabstract摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来75摘要精选三个世界:面向对象的建模75对象创建对象按需创建,显式创建。传统技术往往基于栈分配实体运行时刻对象动态结构多变,而难以根据程序文本预测Eiffel的对象创建基本创建基本创建+初始化featureCreationprocedures精选76对象创建对象按需创建,显式创建。精选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摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来84摘要精选三个世界:面向对象的建模84对象引用回顾C++和Java的相应机制VoidReference,clone,copyandcompare对象引用的问题精选85对象引用回顾C++和Java的相应机制精选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”O2“Susanna”O3b“Almaviva”O4c“Almaviva”namelandlordloved_oneO5“Figaro”O6“Susanna”O7d精选87ShallowanddeepcloningInitia精选Anobjectisamachine88精选Anobjectisamachine88精选Abastractedobjectbeforeafteritemindexput_rightstartforthModel:Price:Manufacture:Size:89精选Abastractedobjectbeforeafte精选Anobjecthasaninterfacebeforeafteritemindexput_rightstartforth90精选Anobjecthasaninterfacebe精选Anobjecthasanimplementationstartforthput_rightbeforeafteritemindex91精选Anobjecthasanimplementat精选Informationhiddingstartforthput_rightbeforeafteritemindex92精选Informationhiddingstartfort小结三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来精选93小结三个世界:面向对象的建模精选93作业(本次作业不用提交)尝试学习用Eiffel语言写一些简单的面向对象程序。可从/下载EiffelStudio亦可简单一些http://smarteiffel.loria.fr/精选94作业(本次作业不用提交)尝试学习用Eiffel语言写一些简单类和对象ClassandObject精选类和对象ClassandObject精选关于对象式语言精选本课程并不系统讲授Eiffel语言但应学会“欣赏”Eiffel语言(比较“纯”)它首先是一个对象式程序设计语言但强调从分析到设计到实现的平滑过渡96关于对象式语言精选本课程并不系统讲授Eiffel语言2摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来97摘要精选三个世界:面向对象的建模3摘要三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来精选98摘要三个世界:面向对象的建模精选4三个世界精选客观世界DVD播放机Whatisreality?复杂性认识的主观性问题世界抽象!AmodelofasubsetoftherealityDVD播放机计算机(软件)世界Amodelofamodelofasubsetofthereality99三个世界精选客观世界DVD播放机2022/12/1InstituteofComputerSoftwareNanjingUniversity现实世界问题世界软件世界Reality抽象精选1002022/11/30InstituteofCompute摘要精选三个世界:面向对象的建模面向对象原则类:对象程序静态的结构对象:运行时刻的结构对象创建:从类到对象对象引用:对象串起来101摘要精选三个世界:面向对象的建模7面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance102面向对象原则精选ObjectOrientationEnca面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance103面向对象原则精选ObjectOrientationEnca回顾:抽象数据类型精选抽象数据类型(ADT):用数学方法定义对象集合和运算集合,仅通过运算的性质刻画数据对象,而独立于计算机中可能的表示方法ADT规约方法代数规范语法部分,公理部分ADT实现E1,E2,E3104回顾:抽象数据类型精选抽象数据类型(ADT):用数学方法定义面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance105面向对象原则精选ObjectOrientationEnca封装精选封装是把过程和数据包围起来,对数据的访问只能通过已定义的界面。DVD播放机106封装精选封装是把过程和数据包围起来,对数据的访问只能通过已定精选封装ProfessorClarkneedstobeabletoteachfourclassesinthenextsemester.SubmitFinalGrades()AcceptCourseOffering()TakeSabbatical()ProfessorClarkSetMaxLoad()Name:JClarkEmployeeID:567138HireDate:07/25/1991Status:TenuredDiscipline:FinanceMaxLoad:4SetMaxLoad(4)107精选封装ProfessorClarkneedstob精选封装—信息/实现隐藏InterfaceClientDeposit()Withdraw()Transfer()BalanceinsterestYTDOwnerAccount_number
Deposit(){…}Withdraw(){…}Transfer(){…}108精选封装—信息/实现隐藏InterfaceClientDep精选封装封装使得对象在抽象所界定的范围内保持相对的独立,从而保证对象设计和对象实施方法的可靠分离。——设计者和使用者分离!封装可以防止由于程序模块之间的互相依赖性而导致程序“不稳定”——不会因某个部分的修改而导致整个系统许多部分都发生改动。封装是相对的!不能也没有必要阻止编程人员去查看实施细节。109精选封装封装使得对象在抽象所界定的范围内保持相对的独立,从而精选封装vs.继承矛盾吗?No!封装性主要指的是对象的封装性,引入继承机制后,对象仍然是封装地很好的实体,其它对象与它通信只能发送消息。相似性:共享代码!继承:静态共享代码封装:动态共享代码110精选封装vs.继承矛盾吗?No!16精选模块化传统的模块划分方法:要求组成的子程序(模块)有实际意义和明确的某个功能功能分解和结构分解OO的模块划分目标:生成一组有助于降低系统开发费用的模块,通过模块划分所得到的模块应该能够保证可以独立的生成和修改,每个模块的结构应该足够简单111精选模块化传统的模块划分方法:要求组成的子程序(模块)有实际精选模块化与抽象和封装密切相关模块的划分是以抽象出来的对象的性质和功能为依据的模块是封装得以实现的技术保障Booch:“模块化是反映一个被分解成一组相关联的松散结合模块组成系统的一个特性。”模块化以模块为基础112精选模块化与抽象和封装密切相关18精选模块与类型的统一模块是软件分解的单元,是语法概念类型是某些动态对象的静态描述,是语义概念传统语言模块与类型分离对象语言模块与类型统一类型:类是抽象数据类型的实现模块:类是对象式程序的基本组成单元基于类的面向对象的语言机制的强有力之处在于“类”统一了类型和模块113精选模块与类型的统一模块是软件分解的单元,是语法概念基于类的面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance114面向对象原则精选ObjectOrientationEnca精选层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不够!层次性是对抽象的排序和定位类结构关系(“isa”)对象结构关系(“partof”)实现方式继承:子类,父类单继承,多继承聚合:拥有关系/组合关系115精选层次性封装性帮助隐藏细节;模块化使结构更加有序,但仍然不精选继承单继承CheckingSavingsSuperclass(parent)SubclassesInheritanceRelationshipAncestorDescendents116精选继承单继承CheckingSavingsSupercla精选继承多继承Usemultipleinheritanceonlywhenneededandalwayswithcaution!MultipleInheritance117精选继承多继承Usemultipleinheritanc精选继承继承作为模块扩展机制,体现开闭原则,较好地支持软件的复用。继承作为类型特化机制,体现分类方法,更合理地支持子类型实现。继承也是多态和动态绑定机制的基础。118精选继承继承作为模块扩展机制,体现开闭原则,较好地支持软件精选子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法“Toprogramistounderstand.”特化:包含范围变小,行为特殊化扩展:增加新的操作重定义:改变行为119精选子类对父类的扩展与特化继承表达的是一种分类演绎的认识方法精选TheOpen-ClosedPrinciple(OCP)动机:软件是变化的!开闭原则:“ClosedforModification;OpenforExtension”——对修改关闭,对扩展开放!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面向对象原则精选ObjectOrientationEncapsulationAbstractionPolymorphismInheritance126面向对象原则精选ObjectOrientationEnca精选多态多态性使指相同的操作或函数、过程可作用于多种类型的对象上并获得不同的结果。不同的对象,收到同一消息可以产生不同的结果,这种现象称为多态性。多态性允许每个对象以适合自身的方式去响应共同的消息多态性增强了软件的灵活性和重用性。127精选多态多态性使指相同的操作或函数、过程可作用于多种类型的对精选多态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];//向数组里添加类型
for(inti=0;i<s.length;i++)s[i]=randShape();//用多态的方法调用
for(inti=0;i<s.length;i++)s[i].draw();}}
128精选多态ShapeCircleTriangleSquared精选多态和动态绑定通过类继承机制实现子类型,允许子类重定义父类的操作。这样父类型变量(对象引用)及其上的的操作必然是多态的。这就在实现上要求动态绑定机制129精选多态
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 认识三角形第4课时三角形的高 教学设计-2024-2025学年北师大版数学七年级下册
- 600元美容馆合同范本
- 受聘合同范本
- 劳务雇佣责任合同范本
- 双方交付款合同范本
- 保证质押合同范本
- 发廊股东入股合同范本
- 《送元二使安西》教案设计
- 劳务合同范本兼职
- 保定市电梯维保合同范本
- 《淞沪会战》课件
- 《智能制造技术基础》课件-第4章 加工过程的智能监测与控制
- 初一家长会课件96108
- 罪犯正常死亡报告范文
- 《企业文化概述》课件
- 某地源热泵毕业设计
- (三级)工业机器人运用与维护理论考试复习题库(含答案)
- 2024年广东省公务员录用考试《行测》真题及解析
- 高中英语必背3500单词表(完整版)
- 房产中介居间服务合同模板样本
- 海洋工程装备保险研究
评论
0/150
提交评论