Q11 of 17 · Framework design
How do the Factory and Strategy design patterns apply to test automation frameworks?
Framework designSeniorframework-designfactory-patternstrategy-patterndesign-patternsadvanced
Short answer
Short answer: Factory pattern centralises the creation of objects (drivers, API clients) behind a method that returns the right implementation based on config — decoupling test code from concrete classes. Strategy pattern swaps algorithms (retry logic, screenshot capture, environment selection) at runtime without if-else chains.
Detail
Factory pattern — WebDriver creation:
public class DriverFactory {
public static WebDriver getDriver(String browser) {
return switch (browser.toLowerCase()) {
case "chrome" -> new ChromeDriver(chromeOptions());
case "firefox" -> new FirefoxDriver(firefoxOptions());
case "edge" -> new EdgeDriver(edgeOptions());
default -> throw new IllegalArgumentException("Unsupported: " + browser);
};
}
}
// In BaseTest:
driver = DriverFactory.getDriver(System.getProperty("browser", "chrome"));
Tests never know which browser is running — they just use driver. Cross-browser testing via mvn test -Dbrowser=firefox.
Strategy pattern — environment-aware API client:
// Strategy interface
interface AuthStrategy {
authenticate(client: HttpClient): Promise<void>;
}
// Concrete strategies
class OAuth2Strategy implements AuthStrategy {
async authenticate(client: HttpClient) {
const token = await client.post('/oauth/token', clientCredentials);
client.setHeader('Authorization', `Bearer ${token}`);
}
}
class ApiKeyStrategy implements AuthStrategy {
async authenticate(client: HttpClient) {
client.setHeader('X-API-Key', config.apiKey);
}
}
// Context — selects strategy at runtime
class ApiClient {
constructor(private auth: AuthStrategy) {}
async init() { await this.auth.authenticate(this); }
}
// Usage: switch auth strategy via config, not code change
const client = new ApiClient(env === 'prod' ? new OAuth2Strategy() : new ApiKeyStrategy());
Combined — Factory returns Strategy:
function createApiClient(env: string): ApiClient {
const strategy = env === 'prod' ? new OAuth2Strategy() : new ApiKeyStrategy();
return new ApiClient(strategy);
}
// WHAT INTERVIEWERS LOOK FOR
Factory for object creation (browser selection is the canonical example). Strategy for swappable algorithms (auth, retry, environment). A combined usage showing they complement each other.