本文介绍了里斯科夫替代原则的一个例子是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说Liskov替代原理(LSP)是面向对象设计的基本原理.它是什么,它的用法有哪些示例?

解决方案

李斯科夫替代原则(LSP, lsp )是面向对象编程中的一个概念,指出:

LSP的核心是接口和协定,以及如何决定何时扩展课程与使用诸如组合之类的另一种策略来实现目标.

我看到的最有效的方式来说明这一点是在 Head First OOA& D .他们提出了一个场景,在该场景中,您是一个项目的开发人员,旨在为策略游戏构建框架.

他们展示了一个代表板的类,如下所示:

所有方法都将X和Y坐标作为参数来定位Tiles的二维数组中的图块位置.这样一来,游戏开发人员就可以在游戏过程中管理棋盘中的各个单元.

这本书继续更改要求,说游戏框架还必须支持3D游戏板才能容纳具有飞行功能的游戏.因此引入了ThreeDBoard类,该类扩展了Board.

乍看之下,这似乎是一个不错的决定. Board提供HeightWidth属性,而ThreeDBoard提供Z轴.

当您查看从Board继承的所有其他成员时,它会崩溃. AddUnitGetTileGetUnits等方法都使用Board类中的X和Y参数,但是ThreeDBoard也需要Z参数.

因此,您必须再次使用Z参数实现这些方法. Z参数没有Board类的上下文,并且从Board类继承的方法失去了其含义.试图将ThreeDBoard类用作其基类Board的代码单元将非常不幸.

也许我们应该找到另一种方法. ThreeDBoard应该由Board对象组成,而不是扩展Board. Z轴的每单位1个Board对象.

这使我们能够使用良好的面向对象原理,例如封装和重用,并且不会违反LSP.

I have heard that the Liskov Substitution Principle (LSP) is a fundamental principle of object oriented design. What is it and what are some examples of its use?

解决方案

The Liskov Substitution Principle (LSP, lsp) is a concept in Object Oriented Programming that states:

At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.

The most effective way I have seen to illustrate this point was in Head First OOA&D. They present a scenario where you are a developer on a project to build a framework for strategy games.

They present a class that represents a board that looks like this:

All of the methods take X and Y coordinates as parameters to locate the tile position in the two-dimensional array of Tiles. This will allow a game developer to manage units in the board during the course of the game.

The book goes on to change the requirements to say that the game frame work must also support 3D game boards to accommodate games that have flight. So a ThreeDBoard class is introduced that extends Board.

At first glance this seems like a good decision. Board provides both the Height and Width properties and ThreeDBoard provides the Z axis.

Where it breaks down is when you look at all the other members inherited from Board. The methods for AddUnit, GetTile, GetUnits and so on, all take both X and Y parameters in the Board class but the ThreeDBoard needs a Z parameter as well.

So you must implement those methods again with a Z parameter. The Z parameter has no context to the Board class and the inherited methods from the Board class lose their meaning. A unit of code attempting to use the ThreeDBoard class as its base class Board would be very out of luck.

Maybe we should find another approach. Instead of extending Board, ThreeDBoard should be composed of Board objects. One Board object per unit of the Z axis.

This allows us to use good object oriented principles like encapsulation and reuse and doesn’t violate LSP.

这篇关于里斯科夫替代原则的一个例子是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 13:51