The Scenario
I\'m making a program in Java that involves cars.
NOTE: I\'ve simplified this scenario (to the best of my ability) to make
You have to say it someplace - there's no getting around that. If you have many more kinds of Cars, you'll have to specify those attributes somewhere.
I don't see where subclassing helps you much, unless you can identify families of cars that are similar (e.g. sports cars, mini-vans, etc.).
One way to centralize all those attributes in one place is to instantiate Car using a factory method (it has a nice symmetry with manufacturing of physical cars, too).
Make the Car constructor private; have an enumeration of CarType that is the key into a Map of attributes for each type; pass in the CarType and get back a Car, fully initialized.
public class Car {
private static final Map> DEFAULT_ATTRIBUTES;
private Map attributes;
static {
DEFAULT_ATTRIBUTES = new HashMap>();
// Insert values here
}
private Car(Map initializers) {
this.attributes = new HashMap(initializers);
}
public static Car create(CarType type) {
return new Car(DEFAULT_ATTRIBUTES.get(type));
}
}