南京大学-软件工程-15 面向对象信息隐藏_第1页
南京大学-软件工程-15 面向对象信息隐藏_第2页
南京大学-软件工程-15 面向对象信息隐藏_第3页
南京大学-软件工程-15 面向对象信息隐藏_第4页
南京大学-软件工程-15 面向对象信息隐藏_第5页
已阅读5页,还剩31页未读 继续免费阅读

下载本文档

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

文档简介

《计算与软件工程II》

Ch15“面向对象”的信息隐藏丁二玉南京大学软件学院InformationHidingEachmodulehidestheimplementationofanimportantdesigndecision(secrets)sothatonlytheconstituentsofthatmoduleknowthedetails3DesignSecretsneedtohide…PrimarySecret:ResponsibilityChangeHiddeninformationthatwasspecifiedtothesoftwaredesignerFromSRSSecondarySecret:ImplementationChangeTheimplementationdecisionsmadebythedesignerwhenimplementingthemoduledesignedtohidetheprimarysecret变化;MainContentsEncapsulationWhatshouldbehiding?Howtohidingchange?Encapsulation(1)EncapsulationallowstheprogrammertogroupdataandthesubroutinesthatoperateonthemtogetherinoneplaceResponsibilityEncapsulation(2)hideirrelevantdetailsfromtheuseraclasscanbedividedintotwoparts,theuserinterfaceandtheimplementation.Theinterfaceisthevisiblesurfaceofthecapsule.describestheessentialcharacteristicsofobjectsoftheclasswhicharevisibletotheexteriorworldTheimplementationishiddeninthecapsule.Theimplementationhidingmeansthatdatacanonlybemanipulated,thatisupdated,withintheclass,butitdoesnotmeanhidinginterfacedata. NewViewofEncapsulationOld/Beginner/Implementationviewofencapsulation:

hidingdatainsideanobjectNewview:hidinganything,including:Data(implementation)Structure(implementation)Otherobject(implementation)Type(derivedclasses)Change/vary(designdetails)…EncapsulationCorrectly——ADTADT=AbstractDataTypeAconcept,notanimplementationAsetof(homogeneous)objectstogetherwithasetofoperationsonthoseobjectsNomentionofhowtheoperationsareimplementedEncapsulation=dataabstraction+typedataabstraction:groupdataandoperationType:hidingimplementation,makeusagecorrectlyWhytype?Atypemaybeviewedasasetofclothes(orasuitofarmor)thatprotectsanunderlyinguntypedrepresentationfromarbitraryorunintendeduse.Itprovidesaprotectivecoveringthathidestheunderlyingrepresentationandconstrainsthewayobjectsmayinteractwithotherobjects.Inanuntypedsystemuntypedobjectsarenakedinthattheunderlyingrepresentationisexposedforalltosee.EncapsulateDataIfneeded,useAccessorsandMutators,NotPublicMembers

AccessorsandMutatorsismeaningfulbehaviorConstraints,transformation,format…publicvoidsetSpeed(doublenewSpeed){ if(newSpeed<0){ sendErrorMessage(...); newSpeed=Math.abs(newSpeed); } speed=newSpeed;}EncapsulatestructuresSeechapter16IteratorPatternReferencesandCollectionData-Type!Encapsulateotherobjects

CollaborationDesignComposition;delegationEncapsulatetype(subclass)LSPpointerstosuperclassesorinterfaces;AllderivedclassesmustbesubstituteablefortheirbaseclassEncapsulateChange(orvary)

Identifytheaspectsofyourapplicationthatmaychange(orvary)andseparatethemfromwhatstaysthesame.Takethepartsthatchange(vary)andencapsulatethem,sothatlateryoucanalterorextendthepartsthatvarywithoutaffectingthepartsthatdon’t.SeeDIPandOCPLaterEncapsulateImplementationDetailDataStructureOtherobjectTypeChange/vary…Principle#1:MinimizeTheAccessibilityofClassesandMembersAbstractionAnabstractionfocusesontheoutsideviewofanobjectandseparatesanobject’sbehaviorfromitsimplementationEncapsulationClassesshouldnotexposetheirinternalimplementationdetailsMainContentsEncapsulationHowtohidingchange?ExampleofResponsibility

ChangeCopyReadKeyboardWritePrintervoidCopy(ReadKeyboard&r,WritePrinter&w){

intc;

while((c=r.read())!=EOF)

w.write(c);}WriteDiskvoidCopy(ReadKeyboard&r,WritePrinter&wp,WriteDisk&wd,OutputDevicedev){

intc;

while((c=r.read())!=EOF)

if(dev==printer)wp.write(c);elsewd.write(c);}Howto…AbstractionisKey...usingpolymorphicdependencies(calls)ExampleofResponsibility

ChangeDiskWriter::Write(c){ WriteDisk(c);}CopyKeyboardReaderPrinterWriterDiskWritervoidCopy(ReadKeyboard&r,WritePrinter&w){

intc;

while((c=r.read())!=EOF)

w.write(c);}Principle10:

Open/ClosedPrinciple(OCP)Softwareentitiesshouldbeopenforextension,butclosedformodificationB.Meyer,1988/quotedbyR.Martin,1996Beopenforextensionmodule'sbehaviorcanbeextendedBeclosedformodificationsourcecodeforthemodulemustnotbechanges统计数据表明,修正bug最为频繁,但是影响很小;新增需求数量一般,但造成了绝大多数影响Modulesshouldbe

writtensotheycanbeextended

without

requiringthemtobemodifiedOCPRTTIisuglyanddangerousRTTI=Run-TimeTypeInformationIfamoduletriestodynamicallycastabaseclasspointer

toseveralderivedclasses,anytimeyouextendthe

inheritancehierarchy,youneedtochangethemodulerecognizethembytypeswitchorif-else-ifstructuresRTTIisUglyandDangerous!//

RTTIviolating

the

//open-closed

principleandLSP

class

Shape

{}

class

Square

extends

Shape

{

void

drawSquare()

{

//

draw

}

}

class

Circle

extends

Shape

{

void

drawCircle()

{

//

draw

}

}

void

drawShapes(List<Shape>

shapes)

{

for

(Shape

shape

:

shapes)

{

if

(shapes

instanceof

Square)

{

((Square)

shapes).drawSquare();

}

else

if

(shape

instanceof

Circle)

{

((Circle)

shape).drawCircle();

}

}

}

//

AbstractionandPolymorphismthat

does

//not

violate

the

open-closed

principleandLSP

interface

Shape

{

void

draw();

}

class

Square

implements

Shape

{

void

draw()

{

//

draw

implementation

}

}

class

Circle

implements

Shape

{

void

draw()

{

//

draw

implementation

}

}

void

drawShapes(List<Shape>

shapes)

{

for

(Shape

shape

:

shapes)

{

shape.draw();

}

}

OCPSummaryUseabstractiontogainexplicitclosurePlanyourclassesbasedonwhatislikelytochange.minimizesfuturechangelocationsOCPneedsDIP&&LSPNosignificantprogramcanbe100%closed

R.Martin,“TheOpen-ClosedPrinciple,”1996Principle11:DependencyInversionPrinciple(DIP)I.High-levelmodulesshouldnot

dependonlow-levelmodules.Bothshoulddependonabstractions.II.Abstractionsshouldnotdependondetails.DetailsshoulddependonabstractionsR.Martin,1996DIP:separateinterfacefromimplementation——abstractUseinheritancetoavoiddirectbindingstoclasses:

Designtoaninterface,notanimplementation!ClientInterface

(abstractclass)Implementation

(concreteclass)DIPExampleCopyReaderWriterKeyboardReaderPrinterWriterDiskWriterclassReader{public:virtualintread()=0;};classWriter{public:virtualvoidwrite(int)=0;};voidCopy(Reader&r,Writer&w){intc;while((c=r.read())!=EOF)w.write(c);}DIPProceduralvs.OOArchitectureProceduralArchitectureObject-OrientedArchitectureDIPsummaryAbstractclasses/interfaces:tendtochangelessfrequentlyabstractionsare‘hingepoints’whereitis

easiertoextend/modifyshouldn’thavetomodifyclasses/interfaces

thatrepresenttheabstraction(OCP)ExceptionsSomeclassesareveryunlikelytochange;

thereforelittlebenefittoinserting

abstractionlayerExample:StringclassIncaseslikethiscanuseconcreteclass

directlyasinJavaorC++HowtodealwithchangeOCPstatesthegoal;DIPstatesthemechanism;LSPistheinsuranceforDIPExampleofImplementationChangeDuckquack()swim()display()//otherduck-likemethods…MallardDuckdisplay(){//lookslikeamallard}RedHeadDuckdisplay(){//lookslikea

温馨提示

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

评论

0/150

提交评论