001 package aima.logic.fol; 002 003 import java.util.HashMap; 004 import java.util.Map; 005 006 /** 007 * This class ensures unique standardize apart indexicals are created. 008 */ 009 010 /** 011 * @author Ciaran O'Reilly 012 * 013 */ 014 public class StandardizeApartIndexicalFactory { 015 private static Map<Character, Integer> _assignedIndexicals = new HashMap<Character, Integer>(); 016 017 // For use in test cases, where predictable behavior is expected. 018 public static void flush() { 019 synchronized (_assignedIndexicals) { 020 _assignedIndexicals.clear(); 021 } 022 } 023 024 public static StandardizeApartIndexical newStandardizeApartIndexical( 025 Character preferredPrefix) { 026 char ch = preferredPrefix.charValue(); 027 if (!(Character.isLetter(ch) && Character.isLowerCase(ch))) { 028 throw new IllegalArgumentException("Preferred prefix :" 029 + preferredPrefix + " must be a valid a lower case letter."); 030 } 031 032 StringBuilder sb = new StringBuilder(); 033 synchronized (_assignedIndexicals) { 034 Integer currentPrefixCnt = _assignedIndexicals.get(preferredPrefix); 035 if (null == currentPrefixCnt) { 036 currentPrefixCnt = 0; 037 } else { 038 currentPrefixCnt += 1; 039 } 040 _assignedIndexicals.put(preferredPrefix, currentPrefixCnt); 041 sb.append(preferredPrefix); 042 for (int i = 0; i < currentPrefixCnt; i++) { 043 sb.append(preferredPrefix); 044 } 045 } 046 047 return new StandardizeApartIndexicalImpl(sb.toString()); 048 } 049 } 050 051 class StandardizeApartIndexicalImpl implements StandardizeApartIndexical { 052 private String prefix = null; 053 private int index = 0; 054 055 public StandardizeApartIndexicalImpl(String prefix) { 056 this.prefix = prefix; 057 } 058 059 // 060 // START-StandardizeApartIndexical 061 public String getPrefix() { 062 return prefix; 063 } 064 065 public int getNextIndex() { 066 return index++; 067 } 068 // END-StandardizeApartIndexical 069 // 070 }