Java Reference
In-Depth Information
/**
* @return the totalSaves
*/
public int getTotalSaves() {
return totalSaves;
}
/**
* @param totalSaves the totalSaves to set
*/
public void setTotalSaves(int totalSaves) {
this.totalSaves = totalSaves;
}
}
Each of the other
Player
subclasses is very similar to the
Goalie
class. The
most important code to note is the factory method,
createPlayer
, which can be
used to create new instances of the
Player
class.
Note
To take this example one step further, you can limit the methods that can be ac-
cessed. You do this by returning objects of type
PlayerType
, and only declaring the
accessible methods within that interface.
How It Works
Factories are used to generate objects. Usually they are used to abstract the actual cre-
ation of an object from its creators. This can come in very handy when the creator does
not need to know about the actual implementation details of generating the new object.
The factory pattern can also be useful when controlled access to the creation of an ob-
ject is required. In order to implement a factory, create a class that contains at least one
method that is used for returning a newly created object.
In the solution to this recipe, the
PlayerFactory
class contains a method
named
createPlayer(String)
that returns a newly created
Player
object. This
method doesn't do anything special behind the scenes; it simply instantiates a new
Player
instance depending upon the
String
value that is passed to the method.