Recently in a interview I was asked a very general question \"what is abstract in java\".I gave the definition and it was followed with some other question on abstract as wh
I use often abstract classes in conjuction with Template method pattern.
In main abstract class I wrote the skeleton of main algorithm and make abstract methods as hooks where suclasses can make a specific implementation; I used often when writing data parser (or processor) that need to read data from one different place (file, database or some other sources), have similar processing step (maybe small differences) and different output.
This pattern looks like Strategy pattern but it give you less granularity and can degradated to a difficult mantainable code if main code grow too much or too exceptions from main flow are required (this considerations came from my experience).
Just a small example:
abstract class MainProcess {
public static class Metrics {
int skipped;
int processed;
int stored;
int error;
}
private Metrics metrics;
protected abstract Iterator- readObjectsFromSource();
protected abstract boolean storeItem(Item item);
protected Item processItem(Item item) {
/* do something on item and return it to store, or null to skip */
return item;
}
public Metrics getMetrics() {
return metrics;
}
/* Main method */
final public void process() {
this.metrics = new Metrics();
Iterator
- items = readObjectsFromSource();
for(Item item : items) {
metrics.processed++;
item = processItem(item);
if(null != item) {
if(storeItem(item))
metrics.stored++;
else
metrics.error++;
}
else {
metrics.skipped++;
}
}
}
}
class ProcessFromDatabase extends MainProcess {
ProcessFromDatabase(String query) {
this.query = query;
}
protected Iterator
- readObjectsFromSource() {
return sessionFactory.getCurrentSession().query(query).list();
}
protected boolean storeItem(Item item) {
return sessionFactory.getCurrentSession().saveOrUpdate(item);
}
}
Here another example.