设计模式之策略模式(优化版)
不同的国家身份证不同,识别哈萨克斯坦和乌兹别克斯坦的用户身份证。识别身份证文本信息,并提自身所需要的信息(姓名、身份证号)
抽象策略类
public interface OCRIdentifyStratergy { Customer identify(List<String> list,Customer customer); CountryEnum getCountryCode(); }
实现类
@Component public class KZIdentifyStratergyImpl implements OCRIdentifyStratergy { @Override public Customer identify(List<String> list,Customer customer) { String identityFront = list.get(0); String regex = "ЖОНЛИИН\\s+(\\d+)"; Pattern pattern = Pattern.compile(regex); Matcher math = pattern.matcher(identityFront); if( math.find()){ String identity = math.group(1); customer.setIdentityNumber(identity); customer.setTaxId(identity); } String nameRegex = "ТЕП / ФАМИЛИЯ\\R+(.*?)\\R+.*?АТЫ/ИМЯ\\R+(.*?)(\\R|$)"; Pattern pattern1 = Pattern.compile(nameRegex); Matcher math1 = pattern1.matcher(identityFront); if( math1.find()){ String surname = math1.group(1); String name = math1.group(2); String fullName = name + " " + surname; customer.setContacts(fullName); } return customer; } @Override public CountryEnum getCountryCode() { return CountryEnum.KZ; } }
@Component public class UZIdentifyStratergyImpl implements OCRIdentifyStratergy { @Override public Customer identify(List<String> list, Customer customer) { String identityFront = list.get(0); String nameRegex = "Familiyasi/Surname\\R+(\\w+)\\R+.*?Ismi/Given name\\(s\\)\\R+(\\w+)"; Pattern pattern = Pattern.compile(nameRegex,Pattern.DOTALL); Matcher matcher = pattern.matcher(identityFront); if (matcher.find()) { String surname = matcher.group(1); String givenName = matcher.group(2); String fullName = givenName + " " + surname; customer.setContacts(fullName); } String identityBack = list.get(1); String regex = "Shaxsiy raqami Personal number\\s+(\\d+)"; Pattern pattern1 = Pattern.compile(regex); Matcher math1 = pattern1.matcher(identityBack); if( math1.find()){ String identity = math1.group(1); customer.setIdentityNumber(identity); customer.setTaxId(identity); } return customer; } @Override public CountryEnum getCountryCode() { return CountryEnum.UZ; } }
环境类
@Component @Slf4j public class OCRIdentifyContext implements ApplicationContextAware { private static final ConcurrentHashMap<CountryEnum,OCRIdentifyStratergy> map = new ConcurrentHashMap<>(); @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { Map<String, OCRIdentifyStratergy> map1 = applicationContext.getBeansOfType(OCRIdentifyStratergy.class); map1.forEach((k,v) -> map.put(v.getCountryCode(), v)); log.info("OCR识别策略上下文初始化完成:{}", JSON.toJSONString(map)); } public static OCRIdentifyStratergy getIdentifyStrategy(CountryEnum typeEnum){ return map.get(typeEnum); } }
自定义枚举类(countryEnum)

浙公网安备 33010602011771号