Notes
Factory
The factory pattern puts the decision of which object to create in one place. A driver factory reads the configuration and returns a Chrome driver, a Firefox driver, or a remote driver for a Selenium grid, with the right options. Tests just ask the factory for a driver. Adding Edge, or a cloud grid, means changing one method instead of every test.
static WebDriver create(Config c) {
return switch (c.browser()) {
case "firefox" -> new FirefoxDriver(
firefoxOptions(c));
case "remote" -> new RemoteWebDriver(
c.gridUrl(), chromeOptions(c));
default -> new ChromeDriver(
chromeOptions(c));
};
}
// tests: DriverFactory.create(cfg) Builder
The builder pattern creates objects step by step with readable method names. An order builder starts with sensible defaults, and a test changes only the fields it cares about: for customer Alice, with four notebooks, with the coupon save ten, then build. Compare that with a constructor taking eight arguments in a row. Builders make test data intention revealing and stop tests breaking when a new field is added.
Order order = anOrder()
.forCustomer("alice@shoprung.test")
.with(NOTEBOOK, 4)
.withCoupon("SAVE10")
.build();
every field has a default:
a test sets only what it is
about, here the coupon
records: new Order(...) with 8
arguments is unreadable Fluent and facade
Two related patterns. A fluent interface returns an object from each step so calls chain like a sentence, as the page objects in the Selenium lab did: open, add to cart, open the cart, apply the coupon. A facade hides a long flow behind one simple call: buy, for Alice, four notebooks with save ten, which logs in, adds, applies and orders. Tests that are not about checkout use the facade and stay short.
// fluent: each step returns the
// next page
products.open()
.addToCart("Clean Code ...", "1")
.openCart().applyCoupon("save10");
// facade: one call for a flow
Order o = checkout.buy(alice,
NOTEBOOK, 4, "SAVE10");
// = login + add + coupon + order Strategy
The strategy pattern defines a family of interchangeable behaviours behind one interface. A login strategy can be a UI login that fills the form, or an API login that puts the token into local storage, as in the Selenium lab. Configuration picks one, and tests do not change. The same idea switches environments, test data sources, or wait policies.
interface LoginStrategy {
void logIn(WebDriver d, User u); }
class UiLogin implements ...
// fills the form
class ApiLogin implements ...
// token into localStorage
LoginStrategy login =
cfg.fastLogin() ? new ApiLogin()
: new UiLogin(); Decorator and listeners
A decorator wraps an object to add behaviour while keeping the same interface. Selenium four ships one: the event firing decorator wraps a driver with a listener that is called before and after actions, here logging every click. Tests still use a normal web driver. Test runner listeners, like JUnit extensions or TestNG listeners, apply the same idea to tests: screenshots on failure, timing, reporting.
WebDriverListener logger =
new WebDriverListener() {
public void beforeClick(
WebElement e) {
log.info("click {}", e); } };
WebDriver driver = new
EventFiringDecorator<>(logger)
.decorate(new ChromeDriver());
// same driver API, plus logging Singleton
The singleton pattern gives one shared instance. It is fine for read only configuration loaded once. It is a classic mistake for web drivers: one static driver shared by every test leaks state between tests and makes parallel runs collide. If code needs a driver per thread, use a thread local, or better, create a driver per test through the factory and pass it in.
- OK: read-only Config, loaded once
- NOT OK: a static singleton WebDriver shared by all tests → parallel runs collide → state leaks between tests
- if you need one per thread: ThreadLocal<WebDriver> or a driver per test
Screenplay
The screenplay pattern models users instead of pages. An actor, Alice, has abilities like browsing the web or calling APIs, performs tasks like adding to cart and applying a coupon, and asks questions like the cart total. It scales well for large suites with many journeys and is used by Serenity BDD. For small and medium suites, page objects with flows are usually simpler.
alice.attemptsTo(
AddToCart.the(NOTEBOOK, 4),
ApplyCoupon.code("SAVE10"));
alice.should(seeThat(
CartTotal.displayed(),
equalTo("$49.99")));
actors HAVE abilities (browse,
call APIs), DO tasks, ASK
questions; used by Serenity BDD SOLID for tests
The patterns rest on the SOLID principles. Single responsibility: the cart page and the header are separate classes. Open for extension: a new browser means a new factory case, not edits to tests. Substitution: any login strategy works where a login strategy is expected. Small interfaces. And dependency inversion: tests depend on interfaces like a login strategy or a shop API, not on concrete classes.
- S one reason to change per class (CartPage ≠ Header)
- O add a browser without editing tests (factory)
- L any LoginStrategy works
- I small interfaces
- D tests depend on interfaces (LoginStrategy, ShopApi), not concrete classes
Common mistakes
Pattern mistakes. Using patterns for their own sake, which adds indirection without value. A static singleton driver. Builders with no defaults, so tests still set every field. Facades that hide assertions. Deep inheritance chains instead of composing small objects. And manager or helper classes that do everything and grow forever.
- patterns for their own sake
- a static singleton driver
- builders with no defaults
- facades that assert
- deep inheritance instead of composition
- "manager" classes that do everything
Say it like this
In the interview, name patterns with the problem each solved. Page objects with a fluent style. A driver factory driven by configuration for browsers and the grid. Builders for test data with defaults. A facade for the checkout flow. A strategy for UI or API login. A decorator listener for logging and screenshots. And explain one you avoided: no static singleton driver, one driver per test, so the suite runs in parallel.
- "Page objects with a fluent
- style; a driver factory driven
- by config; builders for test
- data with defaults; a facade
- for checkout; a strategy for UI vs API login; a decorator
- listener for logging and screenshots. No static
- singleton driver: one per test, so it runs in parallel."