OOP design problem
What is good design in this simple case:
Let's say I have a base class Car with a method FillTank(Fuel fuel)
where
fuel is also a base class which have several leaf classes, diesel, ethanol etc.
On my leaf car class DieselCar.FillTank(Fuel fuel)
only a certain type of fuel
is allowed (no surprises there:)). Now here is my concern, according to my interface every car can be tanked with any fuel, but that seems wrong to me, in every FillTank()
implementation chec开发者_开发知识库k the input fuel for the correct type and if not throw error or something.
How can I redesign such case to a more accurate one, is it even possible? How to design a base method which takes a base-class for input without getting these "strange results"?
Use a generic base class (if your language supports it (the below is C#)):
public abstract class Car<TFuel> where TFuel : Fuel
{
public abstract void FillTank(TFuel fuel);
}
Basically this enforces any class that inherits from car to specify which type of fuel it uses. Furthermore, the Car
class imposes a restriction that TFuel
must be some subtype of the abstract Fuel
class.
Lets say we have some class Diesel
which is simple:
public class Diesel : Fuel
{
...
}
And a car which only runs on diesel:
public DieselCar : Car<Diesel>
{
public override void FillTank(Diesel fuel)
{
//perform diesel fuel logic here.
}
}
Object-oriented programming alone cannot handle this problem well. What you need is generic programming (C++ solution shown here):
template <class FuelType>
class Car
{
public:
void FillTank(FuelType fuel);
};
Your diesel car is then just a specific car, Car<Diesel>
.
If there is a hard boundary between types of cars and types of fuel, then FillTank()
has no business being in the base Car
class, since knowing that you have a car doesn't tell you what kind of fuel. So, for this to ensure correctness at compile time, FillTank()
should be defined in the subclasses, and should only take the Fuel
subclass that works.
But what if you have common code that you don't want to repeat between the subclasses? Then you write a protected FillingTank()
method for the base class that the subclass's function calls. Same thing goes for Fuel
.
But what if you have some magic car that runs on multiple fuels, say diesel or gas? Then that car becomes a subclass of both DieselCar
and GasCar
and you need to make sure that Car
is declared as a virtual superclass so you don't have two Car
instances in a DualFuelCar
object. Filling the tank should Just Work with little or no modification: by default, you'll get both DualFuelCar.FillTank(GasFuel)
and DualFuelCar.FillTank(DieselFuel)
, giving you an overloaded-by-type function.
But what if you don't want the subclass to have a FillTank()
function? Then you need to switch to run time checking and do what you thought you had to: make the subclass check Fuel.type
and either throw an exception or return an error code (prefer the latter) if there is a mismatch. In C++, RTTI and dynamic_cast<>
are what I would recommend. In Python, isinstance()
.
a double dispatch can be used for this: accept some fuel before before filling. Mind you that in language that don't support it directly, you introduce dependencies
It sounds like you just want to restrict the type of fuel that goes into your diesel car. Something like:
public class Fuel
{
public Fuel()
{
}
}
public class Diesel: Fuel
{
}
public class Car<T> where T: Fuel
{
public Car()
{
}
public void FillTank(T fuel)
{
}
}
public class DieselCar: Car<Diesel>
{
}
Would do the trick e.g.
var car = new DieselCar();
car.FillTank(/* would expect Diesel fuel only */);
Essentially what you are doing here is allowing a Car
to have specific fuel types. It also allows you to create a car that would support any type of Fuel
(the chance would be a fine thing!). However, in your case, the DieselCar, you would just derive a class from car and restrict it to using Diesel
fuel only.
use the is
operator to check against the accepted classes, and you can throw an exception in the constructor
I think the accepted method would be to have a ValidFuel(Fuel f)
method in your base class that throws some sort of NotImplementedException
(different languages have different terms) if the "leaf" cars don't override it.
FillTank
could be then be entirely in the base class and call ValidFuel
to see if it's valid.
public class BaseCar {
public bool ValidFuel(Fuel f) {
throw new Exception("IMPLEMENT THIS FUNCTION!!!");
}
public void FillTank(Fuel fuel) {
if (!this.ValidFuel(fuel))
throw new Exception("Fuel type is not valid for this car.");
// do what you'd do to fill the car
}
}
public class DieselCar:BaseCar {
public bool ValidFuel(Fuel f) {
return f is DeiselFuel
}
}
In a CLOS-like system, you could do something like this:
(defclass vehicle () ())
(defclass fuel () ())
(defgeneric fill-tank (vehicle fuel))
(defmethod fill-tank ((v vehicle) (f fuel)) (format nil "Dude, you can't put that kind of fuel in this car"))
(defclass diesel-truck (vehicle) ())
(defclass normal-truck (vehicle) ())
(defclass diesel (fuel) ())
(defmethod fill-tank ((v diesel-truck) (f diesel)) (format nil "Glug glug"))
giving you this behaviour:
CL> (fill-tank (make-instance 'normal-truck) (make-instance 'diesel))
"Dude, you can't put that kind of fuel in this car"
CL> (fill-tank (make-instance 'diesel-truck) (make-instance 'diesel))
"Glug glug"
Which, really, is Common Lisp's version of double dispatch, as mentioned by stefaanv.
you can extend your original Car interface
interface Car {
drive();
}
interface DieselCar extends Car {
fillTank(Diesel fuel);
}
interface SolarCar extends Car {
chargeBattery(Sun fuel);
}
}
精彩评论