Peter Penzov Peter Penzov - 4 months ago 10
Java Question

Design factory for Java driver

I would like to create Factory class which returns Object based on String variable. For example:

public class BrowserFactory
{
public BrowserFactory(String browser)
{
switch (browser.toLowerCase())
{
case "chrome":
{
new ChromeDriver();
break;
}
case "firefox":
{
new FirefoxDriver();
break;
}
case "explorer":
{
new InternetExplorerDriver();
break;
}
case "edge":
{
new EdgeDriver();
break;
}
}
}
}


I would like to use it this way:

BrowserFactory sd = new BrowserFactory("chrome");


Can you propose some better way to design this code?

Answer

Your factory should Looks like this:

public class BrowserFactory
{
    private BrowserFactory(){
    }
    public static RemoteWebDriver getDriver(String browser)
    {
        switch (browser.toLowerCase())
        {
            case "chrome":
            {
                return new ChromeDriver();
            }
            case "firefox":
            {
                return new FirefoxDriver();
            }
            case "explorer":
            {
                return new InternetExplorerDriver();
            }
            case "edge":
            {
                return new EdgeDriver();
            }
            default: throw new IllegalArgumentException("Browser not supported")

        }
        return null;
    }

}

And you call it:

RemoteDriver rd = BrowserFactory.getDriver("chrome");