http://www.javaworld.com/javaworld/javaqa/2001-05/02-qa-0511-factory.html?page=1
Anyway,
Every program needs a way to report errors. Consider the following interface:
public interface Trace {You have two implementations -
// 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 );
}
Class FileTrace implements Trace{
}
Class SystemTrace implements Trace{
}
To use any of these classes, you need to instatiate these where ever you need them.
//... some code ...
SystemTrace log = new SystemTrace();
//... code ...
log.debug( "entering loog" );
// ... etc ..
Now if you want to change the trace mechanism in your code. You need to change it everywhere. Instead, we use sthg called as TraceFactory.
We say
Class Tracefactory {
public static Trace getTrace(){
return new SystemTrace();
}
}
And we say in the code :
new Tracefactory().getTrace();
We can thus change the Tracefactory, if we need to change the default tracing!
No comments:
Post a Comment