2.4. Design a class that uses the Factory design pattern - Source Code

Factory method example:

package c2.s4;

/**
 * @author Mikalai Zaikin
 */
public interface Logger {

    // Write out a debug message
    public void debug(String msg);

    // Write out an error message
    public void error(String msg);
}
					

package c2.s4;

import static java.lang.System.out;

/**
 * @author Mikalai Zaikin
 */
public class ConsoleLogger implements Logger {

    ConsoleLogger() {} // Not accessible from other packages !!!

    public void debug(String msg) {
        out.println("DEBUG: " + msg);
    }

    public void error( String msg) {
        out.println("ERROR: " + msg);
    }
}
					

package c2.s4;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mikalai Zaikin
 */
public class FileLogger implements Logger {

    private PrintWriter pw;

    FileLogger() throws IOException { // Not accessible from other packages !!!

        // Throws java.io.FileNotFoundException if the file does not exist
        pw = new PrintWriter(new FileWriter("/tmp/logger.log" ) );
    }

    public void debug(String msg) {
        pw.println("DEBUG: " + msg);
        pw.flush();
    }

    public void error(String msg) {
        pw.println("ERROR: " + msg);
        pw.flush();
    }
}
					

package c2.s4;

import java.io.IOException;

/**
 * @author Mikalai Zaikin
 */
public class LoggerFactory {

    private static Logger l = null;

    public static Logger getLogger() {
        if (l == null) {
            try {
                l = new FileLogger(); // Can fail if the log file does not exist
            } catch (IOException e) {
                l = new ConsoleLogger();
            }
        }
        return l;
    }
}
					

package c2.s4;

/**
 * @author Mikalai Zaikin
 */
public class LoggerTest {
     public static void main(String[] args) {
         LoggerFactory.getLogger().debug("Test debug");
         LoggerFactory.getLogger().error("Test error");
    }
}
					

output:

DEBUG: Test debug
ERROR: Test error
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide