Feel free to clone the example here:

git clone https://zerosimms@bitbucket.org/zerosimms/sense.git

Switch to the branch: WebDriver-Factory

Selenium Factory

Selenium has a factory which can be used in your automated framework to make your life that little bit easier. A great benefit, on-top of it’s ease to setup is that it eliminates Stale objects forming. That is, an object that has lost it identity.

Stale objects can happen when bouncing around web pages using navigation, when you return the elements don’t always have the same ID that Selenium originally assigned to them so it can no longer find them and Bang!! Your script fails! So, the factory can take care of that for you.

The factory also handles lazy objects, this will save your script from bombing out if it can’t find an element because it only instantiates the object when you call it. It can also help keep your scripts just that bit smaller as you don’t need to instantiate your elements.

So how do you use the factory?
In your Page Object class, fairly simply. Add the annotation:

@FindBy(id"element id")
private WebElement myElementID

If your using IntelliJ you can Alt + Enter on the annotation and import or just add:

import org.openqa.selenium.support.FindBy;


Your page class should then look something like this:
Screen Shot 2014-09-20 at 20.26.48

That’s its, you now can use the element in your methods with the comfort of knowing that it will never become stale.
It is a slightly different way of thinking but it does speed up creating scripts especially for small scale projects.

Just to add, though my screen shot uses Xpath, you can use all the standard Selenium search methods ID, CSS, CLASSNAME etc