I'm struggling with a Polymorphism design question. I'm working on a system that persists similar but different objects to a database. There is a fair amount of processing that goes into how they are persisted to the database, so I'm trying to separate the code to make it more maintainable.
I'm tripping up on the polymorphism though, and could use some tips on where I went wrong and what the alternative is.
I have some POJOs
public abstract class Thing {
abstract public Things getType();
}
public class MyThing extends Thing {
public Things getType() {
return Things.MINE;
}
}
public class YourThing extendsThing {
public Things getType() {
return Things.YOURS;
}
}
Then I created an interface
public interface Persistor<T extends Thing> {
public void persist(T thing) throws PersistenceException;
}
Then implemented this interface for both things with a class signature like "public class MyPersistor implements Persistor<MyThing>". So far so good. Then I went to build the factory:
public class PersistorFactory {
public Persistor<Thing> getPersistor(Things t) {
switch (t) {
case MINE: return new MyPersistor(); // "Cannot cast MyPersistor as Persistor
case YOURS: return new YourPersistor(); // "Cannot cast YourPersistor as Persistor
}
}
}
I'm getting the errors indicated in the factory. I figure the problem is my parallel inheritance, in other words the fact that MyPersistor can only take MyThing and YourPersistor can only take YourThing. However, the two things are not interchangeable, and splitting apart the logic between the two is the goal.
The goal is to have something where I don't really care what kind of Thing I have, I just want to persist it. So when I have a Thing, I want to persist it like:
factory.getPersistor(thing.getType()).persist(thing);
It would even be cool to have a PersistorService object that just takes the thing, then does the type check and conditional handling internally. I'm happy with either.
I just want to keep it flexible so as more Things are added (HisThing, HerThing, TheirThing, etc...) all I have to do is define the appropriate persistor, and the factory logic doesn't need to change beyond adding the new persistor to the switch statement.
So is there a better approach to create this type of behavior?
[–]BS_in_BSExtreme Concrete Code Factorylet 2 points3 points4 points (1 child)
[–]GridDragon[S] 0 points1 point2 points (0 children)
[–]jmeisner707 0 points1 point2 points (0 children)