- 3
- 0
- 约9.49千字
- 约 36页
- 2021-01-07 发布于安徽
- 举报
Example of Responsibility Change DiskWriter::Write(c) { WriteDisk(c); } Copy Keyboard Reader Printer Writer Disk Writer void Copy(ReadKeyboard r, WritePrinter w){ int c; while ((c = r.read ()) != EOF) w.write (c); } Principle 10: Open/Closed Principle (OCP) Software entities should be open for extension, but closed for modification B. Meyer, 1988 / quoted by R. Martin, 1996 Be open for extension modules behavior can be extended Be closed for modification source code for the module must not be changes 统计数据表明,修正bug最为频繁,但是影响很小;新增需求数量一般,但造成了绝大多数影响 Modules should be written so they can be extended without requiring them to be modified OCP RTTI is ugly and dangerous RTTI = Run-Time Type Information 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 module recognize them by type switch or if-else-if structures RTTI is Ugly and Dangerous! //?RTTI?violating?the?open-closed?principle and LSP ????class?Shape?{}????class?Square?extends?Shape?{????????void?drawSquare()?{????????????//?draw ????????} ????}????class?Circle?extends?Shape?{????????void?drawCircle()?{????????????//?draw ????????} ????}????void?drawShapes(ListShape?shapes)?{????????for?(Shape?shape?:?shapes)?{????????????if?(shapes?instanceof?Square)?{????????????????((Square)?shapes).drawSquare();????????????}?else?if?(shape?instanceof?Circle)?{????????????????((Circle)?shape).drawCircle(); ????????????} ????????} ????}???? //?RTTI?that?does?not?violate?the?open-closed?principle and LSP ????interface?Shape?{????????void?draw(); ????}????class?Square?implements?Shape?{????????void?draw()?{????????????//?draw?implementation ????????} ????}????class?Circle?implements?Shape?{????????void?draw()?{????????????//?draw?implementation ????????} ????}????void?drawShapes(ListShape?shapes)?{????????for?(Shape?shape?:?shapes)?{????????????shape.draw(); ????????} ????} OCP
原创力文档

文档评论(0)