package org.web3j.protocol; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.DeserializationConfig; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectReader; import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier; import com.fasterxml.jackson.databind.module.SimpleModule; import org.web3j.protocol.core.Response; import org.web3j.protocol.deserializer.RawResponseDeserializer; /** * Factory for managing our ObjectMapper instances. */ public class ObjectMapperFactory { private static final ObjectMapper DEFAULT_OBJECT_MAPPER = new ObjectMapper(); static { configureObjectMapper(DEFAULT_OBJECT_MAPPER, false); } public static ObjectMapper getObjectMapper() { return getObjectMapper(false); } public static ObjectMapper getObjectMapper(boolean shouldIncludeRawResponses) { if (!shouldIncludeRawResponses) { return DEFAULT_OBJECT_MAPPER; } return configureObjectMapper(new ObjectMapper(), true); } public static ObjectReader getObjectReader() { return DEFAULT_OBJECT_MAPPER.reader(); } private static ObjectMapper configureObjectMapper( ObjectMapper objectMapper, boolean shouldIncludeRawResponses) { if (shouldIncludeRawResponses) { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) { return new RawResponseDeserializer(deserializer); } return deserializer; } }); objectMapper.registerModule(module); } objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); return objectMapper; } }
这个类改变了我对工厂模式的看法,之前我认为工厂模式是生产一个类的多个不同子类的对象的,现在看来只产生一个类的对象也可以,不存在不同子类的情况。ObjectMapperFactory只生产ObjectMapper这一个类的对象,只是根据需要提供一个默认生产好的ObjectMapper对象,或根据条件生产定制的ObjectMapper。