Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet96/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   92   93   94   95   96   97   98   99   ...   245
Bog'liq
Java 17 Recipes

 How It Works
Factories are generate objects. They are generally used to abstract the creation 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 object is required. 
To implement a factory, create a class containing at least one method used for returning 
a newly created object.
In the solution to this recipe, the PlayerFactory class contains a 
createPlayer(String) method 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 on the string value passed to the method. Another object with 
access to the PlayerFactory class can use createPlayer to return new Player objects 
without knowing how the object is created. While this does not hide much in the case 
of the createPlayer method, the PlayerFactory abstracts the details of which class 
is being instantiated so that the developer only has to worry about obtaining a new 
Player object.
The factory pattern effectively controls how objects are created and makes it easier 
to create objects of a certain type. Imagine if a constructor for an object took more than 
just a handful of arguments; creating new objects that require more than just a couple of 
arguments can become a hassle. Generating a factory to create those objects so that you 
do not have to hard-code all the arguments with each instantiation can make you much 
more productive!
Chapter 5 ObjeCt-Oriented java


165
5-5. Creating Reusable Objects
 Problem
You want to generate an object that could represent something within your application. 
Furthermore, you want to reuse the object to represent multiple instances. For instance, 
suppose that you create an application that generates statistics and league information 
for different sports teams. In this case, you want to create an object representing a team.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   92   93   94   95   96   97   98   99   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling