I have a hierarchy of classes, and I'd like that each object had an ID of the form Classname-integer
(examples: Car-0
, Car-1
, Motorcycle-0
, Truck-0
, Truck-1
, ...)
The class hierarchy is
Vehicle
Car
Motorcycle
Truck
The problem is: I want to write just once the code that manages IDs and I'm lost in costructors, prototypes, late binding, and so on.
Example of what I'd like to obtain in pseudocode:
car = new Car
anotherCar = new Car
car.id // "Car-0"
anotherCar.id // "Car-1"
truck = new Truck
truck.id // "Truck-0"
the Car
constructor initializes the object id with the current Car available id, and then increments it so that the next new Car will have a different id. This must not affect other classes IDs.
Ideally, I'd like to write the code just in the base class Vehicle
, but I don't know if it is possible.
My current target language is Coffeescript / Javascript but other languages are welcome along with some reasoning on how it works.
How would you solve this?