Factory Method Design Pattern: This creational pattern is used to instantiate an object among a set of classed based on some logic. It works on the feature of Encapsulation. Here the object creation code is not on the client side, but in the factory method.
Sounds lot confusing than it is J I did try to implement it with a problem statement in mind.
Now if you are in charge of building the framework and the developers are going to just implement the logger api which you are going to expose and if you are not sure which logger implementation(log4j or commons logging) the client might approve after couple of days, then this where factory method design patterns might help.
This is how I would design it,
//Interface Logger
package com.dp.example.factorymethod;
public interface Logger extends Serializable{
public boolean isInfo();
public boolean isDebug();
public Boolean isWarn();
public Boolean isError();
}
// Subclass Log4J Implementation
package com.dp.example.factorymethod;
import org.apache.Log4JLogger
public class Log4JLogger implements com.dp.example.factorymethod.Logger{
private transient Logger logger;
public static Log4JLogger getInstance(String classname){
Log4JLogger log4JInstance = new Log4JLogger();
log4JInstance.logger = Logger.getLogger(classname);
return log4JInstance;
}
public boolean isInfo();
public boolean isDebug(){
System.out.println(“You have called Log4J Logger Debug”);
}
public Boolean isWarn();
public Boolean isError();
}
//Subclass Commons Logging Implementation
package com.dp.example.factorymethod;
public class CommonsLogger implements com.dp.example.factorymethod.Logger{
private transient java.util.logging.Logger logger;
public static CommonsLogger getInstance(String classname){
CommonsLogger commonsLoggerInstance = new CommonsLogger ();
commonsLoggerInstance.logger = Logger.getLogger(classname);
return commonsLoggerInstance;
}
public boolean isInfo();
public boolean isDebug(){
System.out.println(“You have called Commons Logger Debug”);
}
public Boolean isWarn();
public Boolean isError();
}
//Factory Class – LoggerFactory
public class LoggerFactory{
public static Logger getLoggerImpl(String Classname, String LoggerType){
//you can get the loggertype from propertis file
If(loggerType.equals(“Log4J”)){
return Log4JLogger.getInstance(classname);
}
else {
return CommonsLogger.getInstance(classname);
}
}
//FactoryMethod – LoggerFactoryMethod// Client Code
public class LoggerFactoryMethod{
public static void main(String[] args){
LoggerFactory loggerFactory = new LoggerFactory();
Logger logger = loggerFactory.getLoggerImpl(“className”,”Log4J”);
Logger.isDebug();
}
Apparently, not the best example, but helped me in understanding this whole thing a little better.
Please feel free to comment incase you found this as a wrong implementation of Factory Method Design Pattern.
No comments:
Post a Comment