001package factory.person;
002import java.util.Random;
003public class PersonFactory {
004        private PersonFactory() {}
005        static private Random random = new Random();
006        static public SSN newSSN(String s) {
007                final int REQUIREDLENGTH = 9;
008                if (null == s || REQUIREDLENGTH != s.length())
009                        throw new IllegalArgumentException();
010                boolean someNonZeroDigit = false;
011                for (int i=0; i<REQUIREDLENGTH; i++) {
012                        char c = s.charAt(i);
013                        if (!Character.isDigit(c))
014                                throw new IllegalArgumentException();
015                        if (0 != Character.digit(c,10))
016                                someNonZeroDigit = true;
017                }
018                if (!someNonZeroDigit)
019                        throw new IllegalArgumentException();
020                return new SSNObj(s);
021        }
022        static public Person newRandomPerson() {
023                return new PersonObj(Integer.toString(random.nextInt()),SSN.INVALID);
024        }
025        static public Person newPerson(String name, String ssn) {
026                return new PersonObj(name,ssn);
027        }
028        static public Person newPerson(String name, SSN ssn) {
029                return new PersonObj(name,ssn);
030        }
031}
032
033final class SSNObj implements SSN {
034        final private String s;
035        final private long l;
036        SSNObj(String s) {
037                this.s = s;
038                this.l = Long.parseLong(s);
039        }
040        public String toString() { return s; }
041        public long toLong() { return l; }
042        // TODO: define equals, hashcode, compareTo
043        public int compareTo(SSN that) { return -1; }
044}
045
046final class PersonObj implements Person {
047        final private String name;
048        final private SSN ssn;
049        PersonObj(String name, SSN ssn) {
050                if (null == name || 0 == name.trim().length())
051                        throw new IllegalArgumentException();
052                this.name = name.trim();
053                this.ssn = ssn;
054        }
055        PersonObj(String name, String ssn) {
056                this(name,PersonFactory.newSSN(ssn));
057        }
058        public String name() { return name; }
059        public SSN ssn() { return ssn; }
060        // TODO: define equals, hashcode, compareTo
061        public int compareTo(Person that) { return -1; }
062}