Java Q & A: use the Factory Method mode
Q: When I read 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 I'll 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 ){
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.