集册 Java实例教程 设计智能常数

设计智能常数

欢马劈雪     最近更新时间:2020-01-02 10:19:05

529
枚举类型可以像其他任何类一样具有状态和行为。


import java.util.HashMap;//from NowJava.com

import java.util.Map;

import java.util.regex.Pattern;


enum FieldType {


    PASSWORD(FieldType.passwordFieldName) {


        @Override

        public boolean validate(String fieldValue) {

            return fieldValue != null && fieldValue.length()>2;

        }

    },


    EMAIL_ADDRESS(FieldType.emailFieldName) {



        @Override//from NowJava.com - 时代Java

        public boolean validate(String fieldValue) {

            return fieldValue != null && fieldValue.length()>4;    

        }

    },


    PHONE_NUMBER(FieldType.phoneFieldName) {


        @Override

        public boolean validate(String fieldValue) {

            return fieldValue != null && fieldValue.length()>6;

        }

    },


    SOCIAL_SECURITY_NUMBER(FieldType.ssnFieldName) {


        @Override

        public boolean validate(String fieldValue) {

            return fieldValue != null && fieldValue.length()>8;

        }


    };  // End of enum constants definition


    private String fieldName;

    

    static final String passwordFieldName = "password";

    static final String emailFieldName = "email";

    static final String phoneFieldName = "phone";

    static final String ssnFieldName = "ssn";


    private FieldType(String fieldName) {

        this.fieldName = fieldName;

    }


    public String getFieldName() {

        return this.fieldName;

    }


    abstract boolean validate(String fieldValue);

    

    private static final Map<String, FieldType> nameToFieldTypeMap = new HashMap<>();


    static {

        for (FieldType field : FieldType.values()) {

            nameToFieldTypeMap.put(field.getFieldName(), field);

        }

    }


    public static FieldType lookup(String fieldName) {

        return nameToFieldTypeMap.get(fieldName.toLowerCase());

    }


    private static void printValid(FieldType field, String fieldValue, boolean valid) {

        System.out.println(field.getFieldName() + 

                           "(\"" + fieldValue + "\") valid: " + valid);

    }


    public static void main(String... args) {

                

        String fieldName = FieldType.passwordFieldName;

        String fieldValue = "1Cxy9";  

        FieldType field = lookup(fieldName);

        printValid(field, fieldValue, field.validate(fieldValue));


        fieldName =
展开阅读全文