dimanche 16 août 2020

Better approach to link a enum class with a constant class

I have one Country enum which has all the countries defined as an enum. I would like to link the region class i.e. RegionAfghanistan with the AFGHANISTAN constant enum in Country class. I have defined a hashmap in RegionAfghanistan which has all the region constants for Afghanistan. Like this, I can have RegionUSA, RegionAustralia, etc and these all are linked to Country enum.

I have an approach as shown below when I call from the main method I get all the regionalist for Afghanistan. I am not sure it is the right way, I would like to know if there is any better approach for doing this. Since this uses hashmap and everything, I am not sure if this is the right thing to do. Can you suggest a better approach, Since I want to link the enum class with another region classes?

public interface Region {

    public Map<String, Regi> getRegionList();
}

public interface RegionMethod {

    public String get3166_2Code();
    public CountryCategory getRegionCategory();
}

public class Regi implements RegionMethod {
    
    private String sub3166Code;
    private CountryCategory regionCat;
    
    Regi (String sub3166Code, CountryCategory regionCat){
        this.sub3166Code = sub3166Code;
        this.regionCat = regionCat;
    }

    @Override
    public String get3166_2Code() {
        return sub3166Code;
    }

    @Override
    public CountryCategory getRegionCategory() {
        return this.regionCat;
    }

}

public class RegionAfghanistan implements Region {

    private static final Map<String, Regi> REGION_LIST = new HashMap<String, Regi>();
    
    static {
        
        REGION_LIST.put("Badakhshān", new Regi ("AF-BDS*", CountryCategory.PROVINCE));
        REGION_LIST.put("Baghlān", new Regi ("AF-BGL*", CountryCategory.PROVINCE));
    }

    @Override
    public Map<String, Regi> getRegionList() {
    
        return Collections.unmodifiableMap(RegionAfghanistan.REGION_LIST);
    }
}

public enum Country {
    
    AFGHANISTAN("Afghanistan","AF","AFG",004, new RegionAfghanistan());
    ........
}

public class MainTemp {

    public static void main(String[] args) {

        System.out.println(Country.AFGHANISTAN.getRegion().getRegionList());
    }
}


Aucun commentaire:

Enregistrer un commentaire