Search code examples
javadesign-patternsfactory-pattern

How can i apply "Factory Pattern" to instantiate Firefox, IE and Chrome Browser instances in Java


so here is what i have:

Browser.java
BrowserFactory.java

ChromiumBrowser.java
InternetExlorer.java
FirefoxBrowser.java
HTMLUnitBrowser.java

SeleniumDriver.java

What i am thinking is that SeleniumDriver.java is a client of the BrowserFactory and will create an instance of a browser depending on which one is selected via a csv file :

  1. ChromiumBrowser
  2. InternetExlorer
  3. FirefoxBrowser
  4. HTMLUnitBrowser

Solution

  • You have loads of ways to implement a factory. It depends on how complex the creation and how fixed the list of entities.

    The enum way:

    public enum BrowserType {
        CHROME {
            public Browser create() {
                return new ChromeBrowser();
            }
        },
        IE {
            public Browser create() {
                return new IeBrowser();
            }
        }
        public abstract Browser create();
    }
    
    // Factory is optional really, the enum does the job.
    public class BrowserFactor {
    
        public Browser create(BrowserType type) {
            return type.create();
        }
    }
    

    The map/strategy way:

    interface BrowserStrategy {
        Browser create();
    }
    
    public class ChromeBrowser implements BrowserStrategy {
        public Browser create() {
            return new ChromeBrowser();
        }
    }
    
    public class BrowserFactor {
        Map<String, BrowserStrategy> ctorStategy = ...; // I'd use DI, but this could be manually created.
        public Browser create(String type) {
            return type.create();
        }
    }
    

    The map/reflection way:

    public class BrowserFactor {
        Map<String, Class<? extends Browser> clazz = ...; // I'd use DI, but this could be manually created.
        public Browser create(String type) {
            return clazz.newInstance();
        }
    }
    

    My preference is to see if your DI framework can handle it for you. If not:

    • Simple creation/fixed entity set - Enum or map/reflection
    • Simple creation/expect the entity set will group - map/reflection
    • Complex creation - map/strategy.