When reading the article "Polymorphism in its purest form", I saw an unfamiliar term "Factory method ". Can you explain what is Factory method and how to use it?
A: Factory method is just the name of A method for instantiating an object. Like a Factory, a Factory method task is to create -- or manufacture -- objects.
Let's look at an example.
Each program must have an error reporting method. Take a look at the following interface:
Code List 1
Public interface Trace {
// Turn on and off debugging
Public void setDebug (boolean debug );
// Write out a debug message
Public void debug (String message );
// Write out an error message
Public void error (String message );
}
Assume that two implementations are written. One implementation (code listing 3) writes information to the command line, and the other (code listing 2) writes information to the file.
Code List 2
Public class FileTrace implements Trace {
Private java. io. PrintWriter pw;
Private boolean debug;
Public FileTrace () throws java. io. IOException {
// A real FileTrace wowould need to obtain the filename somewhere
// For the example Ill hardcode it
Pw = new java. io. PrintWriter (new java. io. FileWriter ("c: race. log "));
}
Public void setDebug (boolean debug ){
This. debug = debug;
}
Public void debug (String message ){
If (debug) {// only print if debug is true
Pw. println ("DEBUG:" + message );
Pw. flush ();
}
}
Public void error (String message ){
// Always print out errors
Pw. println ("ERROR:" + message );
Pw. flush ();
}
}
Code List 3
Public class SystemTrace implements Trace {
Private boolean debug;
Public void setDebug (boolean debug ){
This. debug = debug;
}
Public void debug (String message ){
If (debug) {// only print if debug is true
System. out. println ("DEBUG:" + message );
}
}
Public void error (String message ){
// Always print out errors
System. out. println ("ERROR:" + message );
}
}
To use either of these two classes, you need to do this:
Code list 4
//... Some code...
SystemTrace log = new SystemTrace ();
//... Code...
Log. debug ("entering loog ");
//... Etc...
Now, if you want to change the "Trace implementation" used in the program, you need to modify each class of the instantiation "Trace implementation. There may be a large number of classes using Trace, which requires a lot of work. In addition, you must try to avoid modifying your class as much as possible.
Code List 5
Public class TraceFactory {
Public static Trace getTrace (){
Return new SystemTrace ();
}
}
GetTrace () is a Factory method. In this way, whenever you want to get a Trace reference, you can simply call TraceFactory. getTrace ():
Code List 6
//... Some code...
Trace log = new TraceFactory. getTrace ();