How can I represent key with list of values for each environment type in an Enum?

后端 未结 2 1681
南方客
南方客 2021-01-23 16:04

I have two environment PROD and STAGING. In prod environment we have three datacenters ABC, DEF and PQR and stag

2条回答
  •  礼貌的吻别
    2021-01-23 17:04

    While this is a bit tricky without knowing full implementation I might be able to get you started.

    Enums are interesting in that they are Immutable which solves the declaring constant fields and variables. Here is my attempt to solve what you are looking for.

    public enum Server {
        // Constant style naming because Enums are Immutable objects
        ABC_SERVERS("tcp://machineA:8081", "tcp://machineA:8082"),
        DEF_SERVERS("tcp://machineB:8081", "tcp://machineB:8082"),
        PQR_SERVERS("tcp://machineC:8081", "tcp://machineC:8082"),
        CORP("tcp://machineZ:8081");
    
        /* After the name declaration you can essentially do normal class 
           development
        */ Fields
        private List servers = new ArrayList<>();
        public boolean isProd; // you could use something as simple as a 
        //boolean to determine the environment
    
        // Enums use a private constructor because they are never 
        //instantiated outside of creation of this Enum class
        private Server(String... dataCenter){
    
        // because of the varargs parameter there is a potential for 
        //multiple Strings to be passed
            for (String tcp :
                    dataCenter) {
                this.servers.add(tcp);
            }
    
            // You can access the name property of the Enum that is being created
            if (this.name() == "CORP")
                this.isProd = false;
            else
                this.isProd = true;
    
        }
    
        // You could make the List public but this demonstrates some encapsulation
        public List getServers() {
            return servers;
        }
    }
    

    I then checked that each "machine" was being added in another class

        // these are what I used to check to make sure that each string is being "mapped" correctly
        List prodServer = new ArrayList<>();
        List stagingServer = new ArrayList<>();
    
        for (Server server :
                Server.values()) {
            if (server.isProd) {
                for (String machine :
                        server.getServers()) {
                    prodServer.add(machine);
                }
            }
            else {
                for (String machine:
                        server.getServers()) {
                    stagingServer.add(machine);
                }
            }
        }
    
        System.out.println(prodServer);
    
        System.out.println(stagingServer);
    

    Also note that to get the actual enum names you use the .values() function of the Enum class.

提交回复
热议问题