I have a base class, let's call it DispenseResult that stores the result of a machine operation. I am designing for a family of machines. DispenseResult will contain member variables that are applicable to all machines, such as current drawn during an operation.
I was thinking of having a derived class to model certain specialized machines, e.g. MotorizedDispenseResult which would have member variables pertaining to motor function etc.
A part of the client code is to get these various member variables from DispenseResult (or a derived class) and log them. If I do it the way described above then I'll end up with code like:
void log(DispenseResult result) {
// store results common to all machines
log("current = " + result.getCurrent());
// store results for specialized cases
if (result instance of MotorizedDispenseResult) {
log("error = " + ((MotorizedDispenseRe开发者_运维技巧sult)result).getMotorError());
... etc.
}
}
This is going to get messy as new derived types are created with all the instanceof checking. Is there a cleaner way to do it?
TY, Fred
In OO Design, you would add the behaviour to the class, and simply override it in subclasses to provide more specialized behaviour.
eg:
class DispenseResult
{
String log()
{
return "current = " + getCurrent();
}
}
class MotorizedDispenseResult extends DispenseResult
{
@Override
String log()
{
String s = super.log();
s += "error = " + getMotorError();
return s;
}
}
Option 1
- create a method on the base class, possibly abstract.
- have the subclasses implement the method.
- where you are doing the type check, call the method instead.
That way all the subclass specific deviations live in the subclasses instead of somewhere else.
Option 2
If the functionality needs to live outside the class hierarchy, What I would do is
- define an interface 'Handler' with a method 'execute'. Name according to what it is doing in your app.
- Create an implementation for each subclass.
- Create a
Map<SpecificClass, Handler>
- Where you are doing the if-statement on type, lookup the appropriate handler in the map and call execute.
This why you don't have to write extensive if statements, you can let the map do it for you. This is also easier to test, you can test your Handler impls in isolation.
It depends on what you need from this class. In your example, it seems that you only want a specific error message. You can just add a method getError
to the super class, so subclasses have to override it.
provide a polymorphic method print() in DispenseResult class. Printing themselves is the responsibility of these family of objects anyway.
精彩评论