- In Simple Factory we have a Factory Class(LoggerFactory.java) and We call the createLogger method which returns different implementation of logger
- Logger is a abstract class which has different implementations
Logger.java
public abstract class Logger { abstract void log(String logstring); }
ConsoleLogger.java
public class ConsoleLogger extends Logger{ @Override void log(String logstring) { System.out.println("Logging to Console - "+ logstring); } }
DBLogger.java
public class DBLogger extends Logger{ @Override void log(String logstring) { System.out.println("Logging to Database - "+ logstring); } }
FileLogger.java
public class FileLogger extends Logger{ @Override void log(String logstring) { System.out.println("Logging to File - "+ logstring); } }
LoggerFactory.java
public class LoggerFactory { public enum LoggerType { DATABASE, FILE, CONSOLE; } //The same code could be written using if else block instead of switch case public Logger createLogger(LoggerType loggerType) { Logger logger; switch (loggerType) { case FILE: logger = new FileLogger(); break; case DATABASE: logger = new DBLogger(); break; case CONSOLE: logger = new ConsoleLogger(); break; default: logger = new ConsoleLogger(); break; } return logger; } }
ClientApp.java
public class ClientApp { public static void main(String[] args) { LoggerFactory objLoggerFactory = new LoggerFactory(); Logger logger = objLoggerFactory.createLogger(LoggerFactory.LoggerType.CONSOLE); logger.log("Hello there"); } }
Output
Logging to Console - Hello there