Commits

dannas committed 54bc404

Add adapter pattern.

Comments (0)

Files changed (2)

src/main/java/webcrawler/CLI.java

 package webcrawler;
 
-import java.util.List;
 
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.CommandLineParser;
 import org.apache.commons.cli.HelpFormatter;
 import org.apache.commons.cli.Options;
 import org.apache.commons.cli.ParseException;
+import webcrawler.crawlers.Crawler;
 
-import webcrawler.crawlers.Crawler;
 import webcrawler.crawlers.CrawlerFactory;
 import webcrawler.crawlers.impl.BreadthFirstCrawlerFactory;
+import webcrawler.crawlers.impl.CLICrawlerAdapter;
 import webcrawler.models.observers.Observer;
 import webcrawler.models.parsers.impl.HtmlImageParser;
 
 	private Controller controller;
 
 	// The model
-	private Crawler crawler;
+	private CLICrawlerAdapter crawler;
 
 	private enum Subcommand {IMG};
 
 			printErrorMessage(e.getMessage());
 		}
 
+        Crawler originalCrawler;
 		/* TODO: I would prefer to shield this inside Controller. */
 		if (subcommand == Subcommand.IMG) {
 			CrawlerFactory factory = new BreadthFirstCrawlerFactory();
-			crawler = factory.newInstance(startDomain, new HtmlImageParser(), depth, xmlFlag);
-			controller = new Controller(this, crawler);
+			originalCrawler = factory.newInstance(startDomain,
+                    new HtmlImageParser(), depth, xmlFlag);
+            crawler = new CLICrawlerAdapter(originalCrawler);
+			controller = new Controller(this, originalCrawler);
 		} else {
 			System.exit(1);
 		}

src/main/java/webcrawler/crawlers/impl/CLICrawlerAdapter.java

+package webcrawler.crawlers.impl;
+
+import webcrawler.crawlers.Crawler;
+import webcrawler.models.observers.Observer;
+
+/**
+ * Acts as an adapter for the Crawler functionality.
+ *
+ * <p>The idea is that we only expose a subset of the crawler functionality to
+ * the CLI view layer. For another view technology e.g. a GUI it makes sense to
+ * have the stop functionality implemented.</p>
+ *
+ * <p> Implements the Adapter pattern
+ * http://en.wikipedia.org/wiki/Adapter_pattern </p>
+ * @author dannas
+ */
+public class CLICrawlerAdapter {
+
+    private Crawler crawler;
+
+    public CLICrawlerAdapter(Crawler crawler) {
+        this.crawler = crawler;
+    }
+
+    public void start() {
+        crawler.start();
+    }
+
+    public void notifyObservers(String msg) {
+        crawler.notifyObservers(msg);
+    }
+
+    public void registerObserver(Observer obs) {
+        crawler.registerObserver(obs);
+    }
+
+    public void removeObserver(Observer obs) {
+        crawler.removeObserver(obs);
+    }
+}