




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、计算与软件工程II Ch15 “面向对象”的信息隐藏丁二玉南京大学软件学院Information Hidingn Each module hides the implementation of an important design decision (secrets) so that only the constituents of that module know thedetailsDesign Secrets need to hiden Primary Secret:ResponsibilityChangen Hidden information that was specified
2、to the software designern From SRSn Secondary Secret: Implementation Changen The implementation decisions made by the designer when implementing the module designed to hide the primary secretn 变化;3Main Contents1.EncapsulationWhat should be hiding?1.2.How to hiding change?Encapsulation (1)n Encapsula
3、tion allows the programmer to group data and the subroutines that operate on them together in one placen ResponsibilityEncapsulation (2)n hide irrelevant details from the usern a class can be divided into two parts, the user interface and the implementation.n The interface is the visible surface of
4、the capsule.q describes the essential characteristics of objects of the class which are visible to the exterior worldn The implementation is hidden in the capsule.q The implementation hiding means that data can only be manipulated, that is updated, within the class, but it does not mean hiding inter
5、face data.NewView of Encapsulationn Old/Beginner/Implementation view of encapsulation:hiding data inside an objectn New view: hiding anything, including:q Data (implementation)q Structure (implementation)q Other object (implementation)q Type (derived classes)q Change/vary (design details)q Encapsula
6、tionCorrectly ADTn ADT = Abstract Data Typeq A concept, not an implementationq A set of (homogeneous) objects together with a set of operations on those objectsq No mention of how the operations are implementedn Encapsulation = data abstraction + typeq data abstraction: group data and operationq Typ
7、e: hiding implementation, make usage correctlyWhy type?A type may be viewed as a set of clothes (or a suit of armor) that protects an underlying untyped representation from arbitrary or unintended use.It provides a protective covering that hides the underlying representation and constrains the way o
8、bjects may interact with other objects.In an untyped system untyped objects are naked in that the underlying representation is exposed for all to see.Encapsulate Datan If needed, use Accessors and Mutators, Not Public Membersn Accessors and Mutators is meaningful behaviorq Constraints, transformatio
9、n, formatpublic void setSpeed(double newSpeed) if (newSpeed 0) sendErrorMessage(.);newSpeed = Math.abs(newSpeed);speed = newSpeed;Encapsulatestructuresn See chapter 16 Iterator PatternReferences and Collection Data-Type !Encapsulate other objectsn Collaboration Designq Composition; delegationEncapsu
10、late type(subclass)n LSPq pointers to superclasses or interfaces;All derived classes must be substituteablefor their base classEncapsulate Change (or vary)n Identify the aspects of your application that may change (or vary) and separate them from what stays the same.n Take the parts that change( var
11、y ) and encapsulate them, so that later you can alter or extend the parts that vary without affecting the parts that dont.n See DIP and OCP LaterEncapsulate Implementation Detailn Datan Structuren Other objectn Typen Change/varyn Principle #1: Minimize The Accessibility of Classes and Membersn Abstr
12、actionq An abstraction focuses on the outside view of an object and separates an objects behavior from its implementationn Encapsulationq Classes should not expose their internal implementation detailsMain Contents1. Encapsulation2. How to hiding change?Example of Responsibility Changevoid Copy(Read
13、Keyboard& r, WritePrinter& wp, WriteDisk& wd, OutputDevice dev)int c;while(c = r.read()!= if(dev = printer)wp.write(c);elseEOF)wd.write(c);void Copy(ReadKeyboard& r, WritePrinter&int c;w)while (c = r.read () != EOF)w.write (c);Write DiskWrite PrinterRead KeyboardCopyHow to n Abstraction is Keyq .usi
14、ng polymorphic dependencies (calls)Example of Responsibility Changevoid Copy(ReadKeyboard& r, WritePrinter& w)int c;while (c = r.read () != EOF) w.write (c);Disk WriterPrinter WriterKeyboard ReaderDiskWriter:Write(c)WriteDisk(c);CopyPrinciple 10: Open/Closed Principle (OCP)Be open for extension4modu
15、les behavior can be extended Be closed for modification4source code for the module must not be changes统计数据表明,修正bug最为频繁,但是影响很小;新增需求数量一般,但造成了绝大多数影响Modules should be written so they can be extended without requiring them to be modifiedSoftware entities should be open for extension, but closed for modif
16、icationB. Meyer, 1988 / quoted by R. Martin, 1996OCPn RTTI is ugly and dangerousq RTTI = Run-Time Type Informationq If a module tries to dynamically cast a base class pointer to several derived classes, any time you extend the inheritance hierarchy, you need to change the moduleq recognize them by t
17、ype switch or if-else-ifstructuresRTTI is Ugly and Dangerous!/RTTIviolating the/open-closed principle and LSPclass Shape class Square extends Shape void drawSquare() / drawclass Circle extends Shape void drawCircle() / drawvoid drawShapes(List shapes) for (Shape shape : shapes) if (shapes instanceof
18、 Square) (Square) shapes).drawSquare(); else if (shape instanceof Circle) (Circle) shape).drawCircle();/Abstraction and Polymorphism that does/ not violate the open-closed principle and LSPinterface Shape void draw();class Square implements Shape void draw() / draw implementationclass Circle impleme
19、nts Shape void draw() / draw implementationvoid drawShapes(List shapes) for (Shape shape : shapes) shape.draw();OCPSummaryn Use abstraction to gain explicit closuren Plan your classes based on what is likely to change.q minimizes future change locationsn OCP needs DIP & LSPNo significant program can
20、 be 100% closedR.Martin, “The Open-Closed Principle,” 1996Principle 11: Dependency Inversion Principle(DIP)I. High-level modules should not depend on low- level modules.Both should depend on abstractions.II. Abstractions should not depend on details. Details should depend on abstractionsR. Martin, 1
21、996DIP : separate interface fromimplementation abstractn Use inheritance to avoid direct bindings to classes:Interface (abstract class)ClientImplementation (concrete class)Design to an interface, not an implementation!DIP Exampleclass Reader public:virtual int read()=0;Copyclass Writer public:Reader
22、Writervirtual voidwrite(int)=0;KeyboardReaderPrinterWritervoid Copy(Reader&r, Writer&w)int c;while(c = r.read() !=EOF)w.write(c);DiskWriterDIPProcedural vs. OO ArchitectureProcedural ArchitectureObject-Oriented ArchitectureDIPsummaryn Abstract classes/interfaces:q tend to change less frequentlyq abs
23、tractions are hinge points where it is easier to extend/modifyq shouldnt have to modify classes/interfaces that represent the abstraction (OCP)n Exceptionsq Some classes are very unlikely to change;n therefore little benefit to inserting abstraction layern Example: String classq In cases like this c
24、an use concrete class directlyn as in Java or C+How to dealwith change OCP states the goal; DIP states the mechanism; LSP is the insurance for DIPExample of Implementation ChangeAll ducks quackand swim.The superclass takes care of the implementation codeDuckquack() swim() display()/other duck-like methodsThe display() method is abstract, since all duck subtypes
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 初级社会工作者考试的试题及答案高效解析
- 考会计初级证试题及答案
- 2025年吡哌酸项目提案报告
- 八年级社戏考试题目及答案
- 成语感情测试题及答案
- 快速掌握Msoffice考点技巧试题及答案
- 社会工作的多样性与包容性试题及答案
- 2025办公楼 租赁合同书范文办公楼租赁合同的合同范本
- 植物生理学试题及答案
- 旅游景点讲解员面试题目及答案
- 中考词汇完整版
- 英语试卷【百强校大联考】【天域卷】天域全国名校协作体2024-2025学年第二学期2025届高三年级联考(5.23-5.24)含答案或解析
- Photoshop图像美化的实战经验与分享试题及答案
- 2025届天津市和平区第二十中学数学八下期末复习检测模拟试题含解析
- 政府委托经营协议书
- 江苏省南通市通州区、如东县2025届九年级下学期中考一模化学试卷(含答案)
- (统编2024版)七下语文期末专题总复习课件(共6个专题)新教材
- 【MOOC答案】《电力电子学》(华中科技大学)章节作业期末慕课答案
- 职业技术学院现代通信技术专业人才培养方案(2024版)
- 2020年高考地理试卷(天津)(解析卷)
- 2024北京西城区五年级(下)期末语文试题及答案
评论
0/150
提交评论