Java best practice library creation for flexible class creation (Factory Pattern, abstraction, and interfaces)

StackOverflow https://stackoverflow.com/questions/5328225

Question

Imagine I am a Java software developer for a car manufacturer. I have been tasked with creating a library that will be used by numerous in-house applications. For each type of car model manufactured, I create a java object representing that model. I must be able to track not only current models, but prototype models. The prototype models will have one name that is very likely to change once it goes into production. I need to be able to use the library to account for the prototypes and flex with the name change when they are switched into production.

My question is, what is the best approach for this?

Here are my thoughts...

I have been reading several books for ideas as to best handle this situation. Immediately my mind jumps to using a factory pattern. I would have a CarModelFactory class which would return a concrete object for each model. For example:

public class CarModelFactory() {

    public CarModel createCivicModel() {}
    public CarModel createAccordModel() {}
    public CarModel createPrototype1() {
        return new ModelX();
    }
    public CarModel createPrototype1() {
        return new ModelY();
    }

Would this be the best approach? I feel like there should be another layer of abstraction. Problems I see are:

1) What if ModelX goes into production, I create a method for it and put something else in createPrototype1 method, now programs that call that method get the wrong object

2) How do I handle ModelX changing its name?

I thank you for your time!

Was it helpful?

Solution

The factory model sounds good, but I would suggest a createCarModel(String model) method, which looks up in a map the appropriate object. Then renaming a car model is a simple add/remove in that map. With appropriate synchronization, of course, to prevent a rename and a get from colliding.

The map would likely be Map<String, Class<? extends CarModel>>, and the createCar method would instantiate the class using a no-argument constructor, which you would require of all Cars.

This way, there is no recompile necessary any time you add or rename a model, as the factory class does not change its set of method signatures.

Additionally, if you override the ClassLoader, you can unload an old model and load up a new model, allowing the actual directory containing your .class files to be kept clean (no old prototype classes that have since been made into real models).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top