I'm writing a program where at the start of the program I take the bit depth of an image. Once I have the bit depth, which is guaranteed to always be one of 8, 16 or 32 bits. Once I have the bit depth I do some processing on the image, and create a few new images based on the output. For creating the images I need to use specific classes, IE FloatProcessor ShortProcessor ByteProcess and their corresponding arrays, float[] short[] and byte[].
What I would like to do is instead of having a switch or a bunch of if's at ev开发者_运维问答ery place I need to determine which one to use. The three classes are all extensions of a class, but even if I were to do it in a method, I would still have to return the base class and I still wouldn't know which type to cast it as where I am using it.
Edit: What I really want is something along the lines of if(depth == 8) #define type ByteProcessor etc for 16 and 32
What about using Generics instead of inheritance? My Java is rusty, so I'll use C++ to demonstrate:
template<class DataT>
class Foo
{
public:
DataT data
void processData()
{
// Do something here
};
};
If you still need a switch statement in the processData function, you would still avoid having to put it all over your code. You may be able to use Generics in combination with the factory method pattern to get what you want.
Hypothetically speaking, let's say that all three inherit from a base TypeProcessor class:
abstract class TypeProcessor {
public abstract Image ProcessImage(Image input);
}
And, you have your specific classes:
class ByteProcessor extends TypeProcessor{
public byte data[];
public Image ProcessImage(Image input) {
//do stuff
return ret;
}
}
Obviously, if your program holds a TypeProcessor
reference, you can't access data
directly (without doing a bunch of type checking and casting and stuff).
The proper solution is to move the code that needs to access data
into the class itself:
class ByteProcessor extends TypeProcessor{
public byte data[];
public Image ProcessImage(Image input) {
//do stuff
data = whatever;
FrobData
Image ret = new Image(data);
return ret;
}
void FrobData() {
for(i = 0; i < data.length; i++) {
data[i] = (data[i] + 1) % 64;
}
}
}
This is obviously a contrived and very incorrect example, but it should give you the general idea.
This will introduce some code redundancy, but I assume that the calculations are different enough between different types not to warrant a more complicated solution.
精彩评论