Java Reference
In-Depth Information
As an example, suppose you have an abstract class called Account , subclassed to NormalAccount
and VIPAccount . Maybe the VIPAccount gets a bonus on creation, or a bonus every time funds are
added, but the exact details of the implementation are not important.
Instead of directly using these objects as is, the factory pattern abstracts away the creation of them
by defining separate creation methods that can be overridden. For the account example, the factory
pattern can thus be implemented as follows:
public class AccountFactory {
public Account createAccount(String name, double amount) {
return new NormalAccount(name, amount);
}
}
public class VIPAccountFactory extends AccountFactory {
public Account createAccount(String name, double amount) {
return new VIPAccount(name, amount);
}
}
In other parts of the code, either of the following can be defined:
AccountFactory factory = new AccountFactory();
Or:
AccountFactory factory = new VIPAccountFactory();
Either one can call the same createAccount method to create the appropriate account.
Note that you can also choose to implement the factory methods directly in the account classes as
static methods, making the constructor of the class private. This is another pattern that shows up a
lot in Java projects.
Again, in other cases, different factory classes implement a single interface class. Sometimes, all fac-
tory classes subclass an abstract factory superclass (this is specifically referred to as the “abstract
factory pattern”) to encapsulate multiple related creation methods. Consider, for example, the
abstract factory class FurnitureFactory , which provides abstract definitions for createChair()
and createTable() , among others. This abstract factory can then be subclassed to the concrete
WoodFurnitureFactory and PlasticFurnitureFactory classes, which would each create corre-
sponding objects ( WoodChair , PlasticTable , and so on), all of which are also subclasses of abstract
Chair and Table classes. The benefit from using this pattern lies in the fact that all remaining code
using these factories can work with the abstract Chair and Table classes, instead of the specific ver-
sion the factory created. This approach retains more levels of abstraction.
Another reason that factory classes are often applied is to create a centralized location to keep a
list of all created objects. For instance, you might opt to keep a list of all created accounts in the
AccountFactory class and provide methods to easily retrieve a specific account later on. This is
fine in some cases, but just as with the singleton pattern, you should take care not to construct
overloaded factory classes containing too much behavior and logic. On a similar note, you might
encounter factory objects that are also singletons. When this happens, keep an eye out for possible
ways to restructure and streamline the affected code.
Search WWH ::




Custom Search