Implementing the same behaviour with different types
OK, first of all of this is done in Java: I deserialize a text file. Each line results in an object from a totally different class hierarchy. Then I give these objects to another object, lets call it a "Writer", which has a method named "write(x)", which then serializes part of that object into another format. Because each deserialized object is from a different class hierarchy, I cannot process each object with the same writer (the contents is also slightly different each time, so that's OK). But what bothers me is, that in the client which is steering this whole process, I have to differentiate between the different objects.
Is there a way, so t开发者_如何学Gohat the "Writer" can decide for himself, what to do, without the client doing that work for him...
Maybe some pseudo code will help.
for(Line line : lines) {
x = one of several kinds of objects is instantiated;
w = one of several kinds of Writers is instantiated, analog to x;
w.write(x);
}
Ideally my code would look like that, but in reallity, each line (except for the last) is a switch statement, because I have to differentiate the objects...
I hope this is not to confusing.
Usually, in such cases you should create an interface Writer:
public interface Writer {
void write(Object o);
}
,
abstract class AbstractWriter, which does some common work and then a number of classes which extend this AbstractWriter.
Then create a Factory class, which will create a necessary writer accordingly to your object type:
public class Factory {
private Factory() {}
public static Writer createWriter(Object o) {
Writer result = null;
if (o.getClass() == MyObject1.class) {
result = new MyFirstObjectWriter();
} else if (...) {
...
} else {
throw new IllegalArgumentException("Unsupported object class" + o.getClass());
}
return result;
}
}
Then the client code will look like this:
for (Line line : lines) {
Object o = readObject(line);
Factory.getWriter(o).write(o);
}
精彩评论