美文网首页
Replace Type Code with Class

Replace Type Code with Class

作者: 坚持编程_lyz | 来源:发表于2017-08-03 02:37 被阅读14次

    类中有一个数值类型码,但他并不影响类的行为,以一个新的类替换数值类型码.

    常量只是一个数值,并没有类型检验,是bug之源.改为使用类的地址值来替代;

    
    public class Person {
    //    public static final int O = BloodGroup.O.getCode();
    //    public static final int A = BloodGroup.A.getCode();
    //    public static final int B = BloodGroup.B.getCode();;
    //    public static final int AB = BloodGroup.AB.getCode();;
    
    //    private int bloodGroup;
        private BloodGroup mBloodGroup;
    
    
    //    public Person(int bloodGroup) {
    //        mBloodGroup = BloodGroup.code(bloodGroup);
    ////        this.bloodGroup = bloodGroup;
    //    }
    
    //    public int getBloodGroupCode() {
    //        return mBloodGroup.getCode();
    //    }
    
    //    public void setBloodGroup(int bloodGroup) {
    //        mBloodGroup = BloodGroup.code(bloodGroup);
    ////        this.bloodGroup = bloodGroup;
    //    }
    
        public BloodGroup getBloodGroup() {
            return mBloodGroup;
        }
    
        public Person(BloodGroup bloodGroup) {
            mBloodGroup = bloodGroup;
        }
    
        public void setBloodGroup(BloodGroup bloodGroup) {
            mBloodGroup = bloodGroup;
        }
    
    
    }
    
    
    
    public class BloodGroup {
        public static final BloodGroup O = new BloodGroup(0);
        public static final BloodGroup A = new BloodGroup(1);
        public static final BloodGroup B = new BloodGroup(2);
        public static final BloodGroup AB = new BloodGroup(3);
        private static final BloodGroup[] values = {O, A, B, AB};
    
        private final int code;
    
        public BloodGroup(int code) {
            this.code = code;
        }
    
        private int getCode() {
            return code;
        }
    
        private static BloodGroup code(int arg) {
            return values[arg];
        }
    
        public static void main(String[] args) {
    //        Person person = new Person(Person.A);
            Person thePerson = new Person(BloodGroup.A);
    
    //        person.getBloodGroupCode();
            thePerson.getBloodGroup().getCode();
    
    //        person.setBloodGroup(Person.AB);
            thePerson.setBloodGroup(BloodGroup.AB);
    
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Replace Type Code with Class

          本文链接:https://www.haomeiwen.com/subject/flsulxtx.html