装饰器的应用 DecoratingStringHashMapper
来源:互联网 发布:超氧换血疗法 知乎 编辑:程序博客网 时间:2024/05/16 06:02
springdataredis 中提供的hashmapper
hashmapper接口
- public interface HashMapper<T, K, V> {
-
- Map<K, V> toHash(T object);
-
- T fromHash(Map<K, V> hash);
- }
hashmapper的实现1- public class BeanUtilsHashMapper<T> implements HashMapper<T, String, String> {
-
- private Class<T> type;
-
- public BeanUtilsHashMapper(Class<T> type) {
- this.type = type;
- }
-
- public T fromHash(Map<String, String> hash) {
-
- T instance = org.springframework.beans.BeanUtils.instantiate(type);
- try {
- BeanUtils.populate(instance, hash);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- return instance;
- }
-
-
-
-
-
- @Override
- public Map<String, String> toHash(T object) {
- try {
-
- Map<String, String> map = BeanUtils.describe(object);
-
- Map<String, String> result = new LinkedHashMap<String, String>();
- for (Entry<String, String> entry : map.entrySet()) {
- if (entry.getValue() != null) {
- result.put(entry.getKey(), entry.getValue());
- }
- }
-
- return result;
-
- } catch (Exception ex) {
- throw new IllegalArgumentException("Cannot describe object " + object, ex);
- }
- }
- }
hashmapper的实现2- public class JacksonHashMapper<T> implements HashMapper<T, String, Object> {
-
- private final ObjectMapper mapper;
- private final JavaType userType;
- private final JavaType mapType = TypeFactory.defaultInstance()
- .constructMapType(Map.class, String.class, Object.class);
-
-
-
-
-
-
- public JacksonHashMapper(Class<T> type) {
-
- this(type, new ObjectMapper());
- mapper.getSerializationConfig().setSerializationInclusion(Inclusion.NON_NULL);
- }
-
- public JacksonHashMapper(Class<T> type, ObjectMapper mapper) {
-
- this.mapper = mapper;
- this.userType = TypeFactory.defaultInstance().constructType(type);
- }
-
- @SuppressWarnings("unchecked")
- public T fromHash(Map<String, Object> hash) {
- return (T) mapper.convertValue(hash, userType);
- }
-
- public Map<String, Object> toHash(T object) {
- return mapper.convertValue(object, mapType);
- }
- }
装饰器--用来优化hashmap的容量- public class DecoratingStringHashMapper<T> implements HashMapper<T, String, String> {
-
- private final HashMapper<T, ?, ?> delegate;
-
- public DecoratingStringHashMapper(HashMapper<T, ?, ?> mapper) {
- this.delegate = mapper;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- public T fromHash(Map hash) {
- return (T) delegate.fromHash(hash);
- }
-
- public Map<String, String> toHash(T object) {
- Map<?, ?> hash = delegate.toHash(object);
- Map<String, String> flatten = new LinkedHashMap<String, String>(hash.size());
- for (Map.Entry<?, ?> entry : hash.entrySet()) {
- flatten.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
- }
- return flatten;
- }
- }
客户端的应用- private HashMapper<QuestShows, String, String> createHashMapper() {
- return new DecoratingStringHashMapper<QuestShows>(new BeanUtilsHashMapper<QuestShows>(QuestShows.class));
- }
装饰器的实现类需要在构造方法中引入被装饰的类以便装饰 0 0