Java Reference
In-Depth Information
need to do any specific work in order to generate new instances. By breaking the work
down into a series of steps, the builder pattern allows objects to implement its builder
methods in different ways. Because the object creator only has access to the builder
methods, it makes creation of different object types much easier.
There are a few classes and interfaces that are necessary for using the builder pat-
tern. First, you need to define a class and its different attributes. As the solution to this
recipe demonstrates, the class may follow the JavaBean pattern (see Recipe 5-5 for
more details). By creating a JavaBean, you will be able to populate the object by using
its setters and getters. Next, you should create an interface that can be used for access-
ing the setters of the object that you created. Each of the setter methods should be
defined in the interface, and then the object itself should implement that interface. As
seen in the solution, the Team object contains the following setters, and each of them
is defined in the TeamType interface:
public void setPlayers(List<Player> players);
public void setName(String name);
public void setCity(String city);
In real life, a team will probably contain more attributes. For instance, you'd prob-
ably want to set up a mascot and a home stadium name and address. The code in this
example can be thought of as abbreviated because it demonstrates the creation of a
generic “team object” rather than show you all the code for creating a team that is true
to life. Because the Team class implements these setters that are defined within the
TeamType interface, the interface methods can be called upon to interact with the ac-
tual methods of the Team class.
After the object and its interface have been coded, the actual builder needs to be
created. The builder consists of an interface and its implementation class. To start, you
must define the methods that you want to have other classes call upon when building
your object. For instance, in the solution to this recipe, the methods
buildNewTeam() , designateTeamCity() , and buildPlayerList() are
defined within the builder interface named TeamBuilder . When a class wants to
build one of these objects later, it will only need to call upon these defined methods in
order to do it. Next, define a builder class implementation. The implementation class
will implement the methods defined within the builder interface, hiding all the details
of those implementations from the object creator. In the solution to this recipe, the
builder class, HockeyTeamBuilder , implements the TeamBuilder interface.
When a class wants to create a new Team object then it simply instantiates a new
builder class.
Search WWH ::




Custom Search