How to Add Buttons and Text to Your JavaFX Project
How to Use Lambda Expressions in Java 8
Java's ArrayList Class

How to Use the Factory Pattern in Java

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.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Using the ToolBar Class in JavaFX
How Can I Tell if a File is Being Deleted in Eclipse?
How to Use the JScrollPane Class to Create Text Areas with Scroll Bars in Java
How to Use the clone Method to Create a Shallow Copy in Java
How to Write Java Code to Delete Several Files at Once
Advertisement

Inside Dummies.com