How to Use the Factory Pattern in Java - dummies

How to Use the Factory Pattern in Java

By Doug Lowe

In Java, the BorderFactory class is an example of a very common design pattern called the Factory pattern. In short, when you use the Factory pattern, you don’t use constructors to create objects. Instead, you use a factory class that has factory methods that create objects for you.

One benefit of the Factory pattern is that the users of the factory class don’t need to know what type of object is actually created. Swing actually defines several classes for borders, for example, all of which implement the Border interface.

If you have to use constructors to create border objects, you have to know about all the border classes. By creating a BorderFactory class that returns Border objects, you have to know only about the BorderFactory class and its methods.

The designers of the Java API could have created a Border class (instead of an interface) that lets you specify what type of border to create via a parameter passed to the constructor, but that approach would have many problems. For starters, the Border class would be complicated because it would have to implement every type of border.

More important, adding a new type of border later is difficult. With the Factory pattern, you can create a new border type easily by (1) creating a class that implements the Border interface for the new border and (2) adding a method to the BorderFactory class to create the new border type.