You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
52 lines
1.8 KiB
52 lines
1.8 KiB
package strategy;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.Map;
|
|
import java.util.function.Supplier;
|
|
|
|
public class CrawlStrategyFactory {
|
|
private static final Map<String, Supplier<CrawlStrategy>> strategyMap = new HashMap<>();
|
|
|
|
static {
|
|
strategyMap.put("dangdang", DangDangStrategy::new);
|
|
strategyMap.put("weather", WeatherStrategy::new);
|
|
strategyMap.put("maoyan", MovieStrategy::new);
|
|
strategyMap.put("12306", Train12306Strategy::new);
|
|
strategyMap.put("csdn", CsdnBlogStrategy::new);
|
|
}
|
|
|
|
public static CrawlStrategy getStrategy(String name) {
|
|
Supplier<CrawlStrategy> supplier = strategyMap.get(name.toLowerCase());
|
|
if (supplier == null) {
|
|
throw new IllegalArgumentException("Unknown strategy: " + name);
|
|
}
|
|
return supplier.get();
|
|
}
|
|
|
|
public static <T extends CrawlStrategy> CrawlStrategy getStrategy(Class<T> strategyClass) {
|
|
try {
|
|
return strategyClass.getDeclaredConstructor().newInstance();
|
|
} catch (Exception e) {
|
|
throw new IllegalArgumentException("Cannot instantiate strategy: " + strategyClass.getName(), e);
|
|
}
|
|
}
|
|
|
|
public static void registerStrategy(String name, Supplier<CrawlStrategy> supplier) {
|
|
if (name == null || supplier == null) {
|
|
throw new IllegalArgumentException("Name and supplier cannot be null");
|
|
}
|
|
strategyMap.put(name.toLowerCase(), supplier);
|
|
}
|
|
|
|
public static boolean hasStrategy(String name) {
|
|
return strategyMap.containsKey(name.toLowerCase());
|
|
}
|
|
|
|
public static int getStrategyCount() {
|
|
return strategyMap.size();
|
|
}
|
|
|
|
public static String[] getStrategyNames() {
|
|
return strategyMap.keySet().toArray(new String[0]);
|
|
}
|
|
}
|