【发布时间】:2019-07-05 00:29:25
【问题描述】:
来自罗伯特·马丁的Agile Principles, Patterns, and Practices in C#,
清单 10-1。违反LSP导致违反OCP
struct Point {double x, y;} public enum ShapeType {square, circle}; public class Shape { private ShapeType type; public Shape(ShapeType t){type = t;} public static void DrawShape(Shape s) { if(s.type == ShapeType.square) (s as Square).Draw(); else if(s.type == ShapeType.circle) (s as Circle).Draw(); } } public class Circle : Shape { private Point center; private double radius; public Circle() : base(ShapeType.circle) {} public void Draw() {/* draws the circle */} } public class Square : Shape { private Point topLeft; private double side; public Square() : base(ShapeType.square) {} public void Draw() {/* draws the square */} }
DrawShape()违反 OCP。它 必须知道 Shape 类的每一个可能的派生词, 并且每当 Shape 的新衍生物出现时,它必须被改变 已创建。
Square和Circle不能替代Shape的事实是 违反 LSP。这种违规行为迫使违反 OCP 绘图形状。因此,违反 LSP 是潜在违反 OCP。
它如何违反 LSP?
(特别是Square和Circle为什么不能代替Shape?)
违反 LSP 如何导致违反 OCP? (我可以看到它直接违反了OCP,但是我无法理解违反LSP如何导致违反OCP。)
【问题讨论】:
标签: solid-principles design-principles liskov-substitution-principle open-closed-principle