I'm working on a searching / organizational algorithm. I use multiple enum
's to define every piece of data that I would want to organize. For example:
enum CarType implements SearchFactor {
CAR, SUV, TRUCK, SEMI, LIMO;
@Override public SearchFactor getSearchFactor() { return this; }
}
and
enum PaintColor implements SearchFactor {
BLACK, WHITE, BLUE, GRAY, RED;
@Override public SearchFactor getSearchFactor() { return this; }
}
where SearchFactor
is:
interface SearchFactor { }
and a sample data class would be:
class Vehicle {
CarType type = CarType.CAR;
PaintColor color = PaintColor.BLA开发者_开发知识库CK;
}
Now for the organization part, I just create an array of included SearchFactor
's and add the enum of what SearchFactor
I would like the algorithm to follow. This is done by incrementally walking through an array of Vehicle
s and comparing the Vehicle
s type
and color
to the array of included SearchFactor
s. For example:
Vehicle[] getVehicleFromSearchFactor(SearchFactor[] factors) {
ArrayList<Vehicle> factoredVehicles = new ArrayList<Vehicle>();
for (Vehicle v : getListOfVehicles()) {
for (SearchFactor f : factors) {
if (v.type == f || v.color == f) {
factoredVehicles.add(v);
break;
}
}
}
return factoredVehicles;
}
Is this good practice? Is this too abstract?
What is the point of a getSearchFactor()
method which only is implemented as return this
?
It is not even used in your getVehicleFromSearchFactor
method.
Other than this, why not. Just make sure that ==
is the right way to compare your search factors. For enum
s this is fine, but for other objects .equals(...)
might be better ... or even .appliesTo(...)
or such.
(Of course, your search in this way allows about no indexing, and has O(number of vehicles × number of search factors) time complexity.)
Agree with answer above re: "getSearchFactor()" method.
In addition to answer above, it seems to me this might be better handled through whatever persistence layer you might be using or some additional indexing technology such as Lucene/Solr.
精彩评论