Java OOPS停车场示例设计
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4453654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java OOPS Parking Lot example Design
提问by SPD
Help me in understanding the power of OOPS in this famous Parking Lotexample. I read this post yesterday trying to figure out perfect lower level design.
在这个著名的停车场示例中帮助我理解 OOPS 的力量。我昨天读了这篇文章,试图找出完美的低级设计。
ParkingLot - ParkingLot has ParkingSpaces ( List of ParkingSpaces) - exit() - entrance() - Update() - int capacity
ParkingLot - ParkingLot 有 ParkingSpaces(ParkingSpaces 列表)-exit()-entry()-Update()-int容量
ParkingSpace -long id -String type (2 wheeler, 4 wheeler etc) -Vehicle (has Vechicle Reference)
ParkingSpace -long id -String 类型(2 轮车、4 轮车等)-车辆(有车辆参考)
Vehicle (interface- any kind of vehicle (two wheeler, four wheeler) - park() - Unpark() abstract methods - has reference of ParkingLot and ParkingSpace
车辆(接口-任何类型的车辆(两轮车、四轮车)-park()-Unpark()抽象方法-参考ParkingLot和ParkingSpace
Car,Truck different kind of vehicles implements Vehicle.
汽车,卡车不同种类的车辆实施车辆。
Is there anything am I missing here...is there any design pattern I need to follow here.. How are we achieving polymorphism in this example.
有什么我在这里遗漏的......这里有没有我需要遵循的设计模式......在这个例子中我们如何实现多态性。
采纳答案by Alex Mullans
Object-oriented programming helps in this situation because your vehicle interface allows you to define similar actions for many different vehicles without having to write those methods/functions for each individual type of vehicle.
面向对象编程在这种情况下很有帮助,因为您的车辆接口允许您为许多不同的车辆定义类似的操作,而无需为每种类型的车辆编写这些方法/函数。
It sounds like you've got a pretty good handle on your classes (ParkingLot, ParkingSpace, Car, Truck) and your interface (Vehicle). If different types of parking spaces had different fields, you could consider a ParkingSpace interface which is then implemented by MotorcycleSpace, CompactSpace, etc. but how you have it now isn't incorrect. Polymorphism comes in as well with your interface.
听起来您对类(ParkingLot、ParkingSpace、Car、Truck)和界面(Vehicle)掌握得很好。如果不同类型的停车位有不同的字段,你可以考虑一个 ParkingSpace 接口,然后由 MotorcycleSpace、CompactSpace 等实现,但你现在如何拥有它并没有错。多态性也出现在你的界面中。
EDIT: With regard to composition, you have a ParkingLot that has ParkingSpaces. If your Vehicle class had Wheels or Options or some other subclass, that would be additional composition.
编辑:关于组合,你有一个有 ParkingSpaces 的 ParkingLot。如果您的 Vehicle 类有 Wheels 或 Options 或其他一些子类,那将是额外的组合。