All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.trang.copiers.CopierFactory Maven / Gradle / Ivy

There is a newer version: 2.5.4
Show newest version
package com.github.trang.copiers;

import com.github.trang.copiers.cglib.CglibCopier;
import com.github.trang.copiers.orika.OrikaCopier;
import net.sf.cglib.core.Converter;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Copier 对象缓存
 *
 * @author trang
 */
public final class CopierFactory {

    private CopierFactory() {
        throw new UnsupportedOperationException();
    }

    private static final String ORIKA = "orika";
    private static final String CGLIB = "cglib";
    private static final String CGLIB_CONVERTER = "cglibConverter";

    public static  OrikaCopier getOrikaCopier(Class sourceClass, Class targetClass) {
        MapperKey mapperKey = new MapperKey<>(ORIKA, sourceClass, targetClass);
        ConcurrentMap, OrikaCopier> orikaCache = CopierFactory.getOrikaCache();
        return orikaCache.computeIfAbsent(mapperKey,
                key -> new OrikaCopier.Builder<>(key.getSourceClass(), key.getTargetClass()).register());
    }

    public static  CglibCopier getCglibCopier(Class sourceClass, Class targetClass) {
        MapperKey mapperKey = new MapperKey<>(CGLIB, sourceClass, targetClass);
        ConcurrentMap, CglibCopier> cglibCache = CopierFactory.getCglibCache();
        return cglibCache.computeIfAbsent(mapperKey,
                key -> new CglibCopier<>(key.getSourceClass(), key.getTargetClass()));
    }

    public static  CglibCopier getCglibCopier(Class sourceClass, Class targetClass, Converter converter) {
        MapperKey mapperKey = new MapperKey<>(CGLIB_CONVERTER, sourceClass, targetClass);
        ConcurrentMap, CglibCopier> cglibCache = CopierFactory.getCglibCache();
        return cglibCache.computeIfAbsent(mapperKey,
                key -> new CglibCopier<>(key.getSourceClass(), key.getTargetClass(), converter));
    }

    private static class SingleHolder {
        private static final ConcurrentMap ORIKA_CACHE = new ConcurrentHashMap<>(1024, 0.75f, 4);
        private static final ConcurrentMap CGLIB_CACHE = new ConcurrentHashMap<>(1024, 0.75f, 4);
    }

    @SuppressWarnings("unchecked")
    private static  ConcurrentMap, OrikaCopier> getOrikaCache() {
        return (ConcurrentMap) SingleHolder.ORIKA_CACHE;
    }

    @SuppressWarnings("unchecked")
    private static  ConcurrentMap, CglibCopier> getCglibCache() {
        return (ConcurrentMap) SingleHolder.CGLIB_CACHE;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy