版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
《计算与软件工程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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年沪科版六年级语文下册阶段测试试卷含答案
- 2025年上外版九年级历史下册阶段测试试卷含答案
- 2025年岳麓版八年级科学上册阶段测试试卷含答案
- 2025年外研版2024四年级数学上册月考试卷含答案
- 2025年人教版(2024)选择性必修2化学上册月考试卷含答案
- 2025年冀教新版选修3生物上册阶段测试试卷含答案
- 2025年北师大版八年级科学下册阶段测试试卷含答案
- 2025年苏教版九年级英语下册月考试卷含答案
- 2025年人教新起点五年级数学上册月考试卷
- 2025年外研版三年级起点选择性必修1物理上册阶段测试试卷含答案
- GB/T 15166.2-2023高压交流熔断器第2部分:限流熔断器
- 老年人能力评估标准解读讲义课件
- 材料报价三家对比表
- 2024年国家公务员考试公共基础知识全真模拟试题及答案(共四套)
- 标准辅助航空摄影技术规范
- 2023年中国人保财险校园招聘笔试参考题库附带答案详解
- hdx7底层黑砖刷写和字库救砖教程bysmartyou
- 年会颁奖晚会颁奖盛典简约PPT模板
- 年产10000吨柑橘饮料的工厂设计
- 雷电知识、雷电灾害防御知识汇总-上(单选题库)
- 导学案 高中英语人教版必修三Unit4 Astronomy the science of the stars
评论
0/150
提交评论