How to model Either / Or in Object Orientated
Hi,
Probably a bit of a basic question I'm trying to get my head around.
What is the correct way to model an either / or relationship in OO (C#), so that the person utilising the type can access the attributes of either item ? I am trying to model a very large object containing many sub types, which in turn contain types, etc.
For instance, a garage can have either a car OR a bike. I want the person using garage to be able to choose either car or bike, and then to access bike.handlebars OR car.engine depending on which they set it to.
E.g:
Garage garage = new Garage();
garage.vehicle = new Bike();
garage.vehicle.handlebars = HandlebarStyle.StreamLine;
Creating a garage object with both these sub types and setting the unused object to null seems wrong.
garage.bike = new Bike(); // set garage.car to null.
garage.car = new Car(); // set garage.bike to null.
Polymorphism allows for the methods to be overridden, not access to attributes.
Using an abstract type (vehicle) and forcing the person using the type to cast it to bike to access bike.handlebars also seems wrong.
((Bike)garage.vehicle).handlebars = HandlebarStyle.StreamLine;
Templates does work, but doesn't seem appropriate if garage contains a number of these either / or types.
How do you model either / or relationships in OO languages ?
Thanks!