I'm not very good at CS domain language, so I hope I can make myself understood.
I'm looking for a DRY way to create objects of on of two types based on a boolean flag. Both types have one method each - differently named - which implements the same logic. This logic I'd like to implement only once (think of an abstract super class here, which won't work in this case though, I think).
Example
To be more concrete, consider this. There are two classes (in my case one inheriting from org.eclipse.core.runtime.jobs.Job and one inheriting org.eclipse.ui.progress.UIJob (which itself extends org.eclipse.core.runtime.jobs.Job)).
Both implement a certain logic (the same!) in a run-type method. For the class extending Job, this method is called run(IProgressMonitor m), for the one extending UIJob this method is called runInUIThread(IProgressMonitor m).
I want to be able to
- Implement the logic only once (DRY!), and for example have both
run()andrunInUIThreadsimply call something likesuper.run(). But because in Java classes cannot extend more than one class, I cannot do something likeMyUIJob extends UIJob, MyAbstractJobwhereMyAbstractJobimplementsabstractRun(), andMyUIJob#runInUIThread(){ super.abstractRun() }. - Start either job (
MyJobandMyUIJob) from the same method (say, in a handler class), depending on, for example, a flagboolean isUIJob.
I've had a brief look at design patterns such as "AbstractFactory" and "Prototype", but these don't seem to work for my case as either would still need "double extension inheritance". (Or am I wrong?)
Hence the question: How can I implement the above in Java?
Aucun commentaire:
Enregistrer un commentaire