Reputation: 5668
I've a case where I've multiple backup data sources. By data source, I mean an abstraction eg. File, NoSql/SQL DB,Diff tables, archives. I've a particular given hierarchy to access the data and I can discard the data of any data source based on certain criteria. Now my question is there any existing design pattern to implement this? Currently I've thought of two approaches but I think they can be improved:
for (long id : ptitleIds) {
if(checkIfInValid(id)) {
continue;
}else if (getFromNdi(result, id)) {
continue;
} else if (getFromCimg(result,id)) {
continue;
} else if (getFromPtitle(result,id)) {
continue;
} else {
result.put(id, EMPTY_OBJECT);
}
}
return result;
Another approach that I tried is shorter but might not be easy to understand is:
for (long id : ptitleIds) {
if(checkIfInValid(id) || getFromNdi(result, id) || getFromCimg(result,id)) || getFromPtitle(result,id)) {
continue;
} else {
result.put(id, EMPTY_OBJECT);
}
}
return result;
In this case data sources are simple functions, inserting and returning true if data is valid.
Upvotes: 3
Views: 2011
Reputation: 32954
I would implement this as a sort of chain of responsibility. In a standard chain of responsibility the next item in the chain is part of the interface for the object, but you can implement similar functionality by using decorators as well.
What I would do is:
Define an interface for loading the data (IDataLoader
) and then have one implementation for each source. Then have a class which chains 2 implementations together (ChainingDataLoader
-> implements IDataLoader
), which is a decorator for a data loader which tries to load with the decorated data loader and if that fails it delegates to a second loader. This second loader can also be a ChainingDataLoader
to allow you to chain as many together as you need.
Upvotes: 2