版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
《计算与软件工程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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 简单的治愈系晚安朋友圈问候语
- 欢欢喜喜猜灯谜作文
- 2024年半导体测试技术项目资金筹措计划书代可行性研究报告
- 2024年公共自行车锁车器设备项目资金需求报告代可行性研究报告
- 《物流运输设备技术》课件
- 新媒体培训心得课件
- 春风课件教学
- 【初中数学课件】和圆有关的比例线段课件
- 黑龙江省哈尔滨师范大学青冈实验中学校2024-2025学年高一上学期期中考试历史试题
- 产品培训课件
- ICD-10疾病编码完整版
- 2023年山东青岛局属高中自主招生物理试卷真题(含答案详解)
- 湖北省2024年中考英语模拟试卷(含答案)
- 市三级公立综合医院绩效考核指标评分细则
- 2024年国家开放大学电大《经济法律基础》形成性考核题库
- 2024考研英语二试题及答案解析
- Unit 4 Section B(2a-2b)课件人教版2024新教材七年级上册英语
- 2024年德州道路旅客运输驾驶员从业资格考试题库
- 中考字音字形练习题(含答案)-字音字形专项训练
- 安全文明施工奖罚明细表
- 全球及中国个人防护装备(PPE)行业市场现状供需分析及市场深度研究发展前景及规划可行性分析研究报告(2024-2030)
评论
0/150
提交评论