j7r15w
Last Updated: July 11, 2016
·
189
· kalinin84

Strategy Pattern (JAVA)

/**
 * ICrawler
 */
public interface ICrawler {
   void scan(String url);
}

/**
 * OldCrawler
 */
public class OldCrawler implements ICrawler {
   @Override
   public void scan(String url) {
      System.out.println("OldCrawler: " + url);
   }
}

/**
 * NewCrawler
 */
public class NewCrawler implements ICrawler {
   @Override
   public void scan(String url) {
      System.out.println("NewCrawler: " + url);
   }
}

/**
 * Strategy context
 */
public class Context {
   private ICrawler crawler;

   public Context(ICrawler crawler){
      this.crawler = crawler;
   }

   public void run(String url) {
      crawler.scan(url);
   }
}

/**
 * Run
 */
public class Run {
    public static void main(String []args) {
        List<Context> contextList = new ArrayList<Context>();

        contextList.add(new Context(new OldCrawler()));
        contextList.add(new Context(new NewCrawler()));

        for (Context context : contextList) {
            context.run("site");
        }
    }
}
Say Thanks
Respond