A Collection of an Abstract Class (or something like that…)

后端 未结 4 1568
[愿得一人]
[愿得一人] 2021-01-05 04:29

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

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-05 04:47

    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));
       }
    }
    

提交回复
热议问题