dimanche 25 juin 2017

Design patterns: many objects of same type with multiple objects of other type

Which would be a good approach if I were to make an application where I had to store all countries in Europe and as well as their respective cities?

I considered using an enum to store the information but since that'd require me to hard-code lots of data I quickly scrapped that idea.

Afterwards I considered something like:

class Country {

    public Country(String name, City... cities) {
        //Stuff
    }
}

That way I'd be able to read cities from a .txt and create objects accordingly thus eliminating the need for manual labor. However, that brings a new issue, where do I store my list of countries? I considered the following:

class Country {

    public Country(String name, City... cities) {
        //Stuff
    }

    public static List<Country> getAllCountries() {
        return countries;
    }
}

but I feel like such code pollutes the structure and cleanliness of the project.

I thought about going with a combination of an enum (Country) and a class (City) but that doesn't feel right either.

Ideally I'd like to be able to access countries like an enum Country.FRANCE or Country.getByName("France") but neither seems like a solution here. So, I'm back to my initial question. What is a good way to go about doing this?

Aucun commentaire:

Enregistrer un commentaire