欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

三更半夜随便来点代码提提神~ 懒人写Factory

程序员文章站 2024-03-21 21:39:22
...
package org.jc.buss.pur.route;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.jc.common.utils.Keys;
import org.jc.utils.InstanceUtil;

public class PurRouteFactory {

    private static final String PACKAGENAME = "org.jc.buss.pur.route.impl";

    private static Map<String, PurRouteSrv> cache = new ConcurrentHashMap<>();

    static {
        List<PurRouteSrv> classList = null;
        try {
            // 获取PACKAGENAME目录下PurRouteSrv类型实例
            classList = InstanceUtil.getInstance(PurRouteSrv.class, PACKAGENAME);
        } catch (Exception e) {
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("PurRouteFactory 启动失败!!!!");
            System.exit(0);
        }
        for (PurRouteSrv srv : classList) {
            srv.init();
            cache.put(srv.getAirCode(), srv);
            System.out.println(srv.getClass() + " init ok.");
        }
    }

    public static PurRouteSrv get(String airCode) {
        PurRouteSrv srv = cache.get(airCode);
        return srv;
    }

    public static Set<String> airs() {
        return cache.keySet();
    }
}
package org.jc.buss.pur;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jc.utils.InstanceUtil;

public class PurServiceFactory {

    private static final String PACKAGENAME = "org.jc.buss.pur";

    private static Map<String, Class<?>> cache = new ConcurrentHashMap<>();

    static {
        try {
            // 获取PACKAGENAME目录下PurService类型Class
            List<Class<?>> classList = InstanceUtil.getClass(PurService.class, PACKAGENAME);
            for (Class<?> clazz : classList) {
                PurService purService = (PurService) clazz.newInstance();
                cache.put(purService.getAirCode(), clazz);
                System.out.println(purService.getClass() + " init ok.");
            }
        } catch (Exception e) {
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
            System.err.println("PurRouteFactory 启动失败!!!!");
            System.exit(0);
        }
    }

    public static IPurService get(String airCode) {
        Class<?> clazz = cache.get(airCode);
        Object obj = null;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        }
        return (IPurService) obj;
    }
}
package org.jc.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.jc.buss.pur.PurService;

public class InstanceUtil {

    public static <T> List<Class<?>> getClass(Class<T> clazz, String packageName)
            throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        List<Class<?>> result = new ArrayList<Class<?>>();

        String _packageName = packageName;
        String packageDirName = _packageName.replace('.', '/');

        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            List<File> fileList = getFiles(url.getPath(), true);
            if (null != fileList && !fileList.isEmpty()) {
                for (File file : fileList) {
                    String className = file.getAbsolutePath().substring(file.getAbsolutePath().indexOf("classes") + 8)
                            .replaceAll(".class", "").replaceAll("\\\\", ".").replaceAll("/", ".");
                    try {
                        Class<?> instance = Class.forName(className, false,
                                Thread.currentThread().getContextClassLoader());
                        if (!clazz.isAssignableFrom(instance) || clazz == instance) {
                            continue;
                        }
                        result.add(instance);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        }
        return result;
    }

    @SuppressWarnings("unchecked")
    public static <T> List<T> getInstance(Class<T> clazz, String packageName)
            throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
        List<T> result = new ArrayList<T>();

        List<Class<?>> classList = getClass(clazz, packageName);
        if (null != classList && !classList.isEmpty()) {
            for (Class<?> c : classList) {
                result.add((T) c.newInstance());
            }
        }

        return result;
    } 

    public static List<File> getFiles(String path, boolean isAddDirectory) {
        List<File> list = new ArrayList<>();
        getFiles(list, path, isAddDirectory);
        return list;
    }

    public static List<File> getFiles(List<File> list, String path, boolean isAddDirectory) {
        File baseFile = new File(path);
        if (baseFile.isFile() || !baseFile.exists()) {
            return list;
        }
        File[] files = baseFile.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                if (isAddDirectory) {
                    getFiles(list, file.getAbsolutePath(), isAddDirectory);
                }
            } else {
                list.add(file);
            }
        }
        return list;
    }
}



相关标签: 代码片段