diff --git a/w11/StrategyFactory.java b/w11/StrategyFactory.java new file mode 100644 index 0000000..e483163 --- /dev/null +++ b/w11/StrategyFactory.java @@ -0,0 +1,42 @@ +package com.example.datacollect.strategy; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import java.util.ArrayList; +import java.util.List; + +public class StrategyFactory { + private static final Logger logger = LoggerFactory.getLogger(StrategyFactory.class); + private final List strategies = new ArrayList<>(); + + public StrategyFactory() { + strategies.add(new HnuNewsStrategy()); + strategies.add(new BlogStrategy()); + strategies.add(new NewsStrategy()); + logger.info("Initialized with {} strategies", strategies.size()); + } + + public CrawlStrategy getStrategy(String url) { + CrawlStrategy bestStrategy = null; + int highestPriority = -1; + + for (CrawlStrategy s : strategies) { + if (s.supports(url) && s.getPriority() > highestPriority) { + bestStrategy = s; + highestPriority = s.getPriority(); + } + } + + if (bestStrategy != null) { + logger.debug("Found strategy {} for URL: {}", bestStrategy.getClass().getSimpleName(), url); + return bestStrategy; + } + logger.debug("No specific strategy found for URL: {}, using default", url); + return new DefaultStrategy(); + } + + public void register(CrawlStrategy strategy) { + strategies.add(strategy); + logger.info("Registered strategy: {}", strategy.getClass().getSimpleName()); + } +}