Why use a factory method?
All factory methods are used to provide a single source from which objects can be created. This source is independant from the client code. If there is a switch statement that is used 10 times in the client code to create an object, then there is a chance that updates to the client code in 10 different places will fail and result in errors and extra debugging time.
If all the client code is located in a seperate dll file, then if the "product's" client code and the factory's client code is updated, it will be possible to just replace the dll file and the program will then contain the new version of the updated code. This is much better for program updates etc.
What is the factory method design pattern?
The factory method is a design pattern that is used to create other objects.
At the heart of the pattern is the factory class that contains a method that is used to create objects derived from the same base class.
The method is called a factory method.
The factory method has a parameter that tells the factory class what concrete class to create.
Example:
Assume that a refrigeration factory makes chest freezers. There may be many different types for chest freezers.
A chest freezer is an abstract class, and each type of chest freezer manufactured is a concrete instance of the abstract chest freezer class.
//abstract class
abstract class ChestFreezer{
private String _model; '_denotes private
private String _marketingCode
public ChestFreezer(String model, String marketingCode){
_model = model;
_marketingCode = marketingCode;
}
}
//one concrete instance of the abstract class
public class ChestFreezer530Litre extends ChestFreezer{
public ChestFreezer530Litre(){
super("CF530","DMF294");
}
}
//another concrete instance of the abstract class
public class ChestFreezer420Litre extends ChestFreezer{
public ChestFreezer420Litre(){
super("CF420","DMF293");
}
}
Normally we would create the concrete classes as follows:
ChestFreezer530Litre myCF530 = new ChestFreezer530Litre();
ChestFreezer420Litre myCF420 = new ChestFreezer420Litre();
We could use a factory class instead to make one central place in order to create ChestFreezer objects.
public class ChestFreezerFactory(){
public ChestFreezerFactory(){
//code here to load all the different types of Chest freezer
//from the database
}
static ChestFreezer createChestFreezer(String model, String marketingCode){
ChestFreezer myCF
switch(model){
case "CF420":
myCF = new ChestFreezer420Litre();
case "CF530":
myCF = new ChestFreezer530Litre();
}
return myCF;
}
}
By using the factory method pattern, we can do this:
ChestFreezer530Litre myCF= ChestFreezerFactory.createChestFreezer("CF530","DMF294");
if(ChestFreezer530Litre=null){
--handle null condition or use an error handler
}