The first design pattern we are about to see is the Factory Method pattern. It is a very simple pattern and widely used. In this pattern we use a factory class which produces objects and delivers them to us. The objects created share a common ancestor. The factory class does nothing but create objects based on a condition passed to it as a parameter.
You might have already used this kind of object creation already in some of your programs without knowing it is a factory pattern. In fact, many programmers use design patterns without knowing their official existence. Following is a Java example for the above representation. I am going to use only java and I presume that the reader has a pretty good grasp of the basics of core Java.
ILogger.java. This is the interface which will be the parent of other concrete logger classes.
public interface ILogger
{
public void log(String str);
}
ConsoleLogger.java. This class will put our log strings onto the screen.
public class ConsoleLogger implements ILogger
{
public void log(String str)
{
System.out.println(str);
}
}
FileLogger.java. This class will store the strings into a file. Where and how the file are stored are out of scope for our discussion here because we concentrate only on the pattern.
public class FileLogger implements ILogger
{
private File logFile;
public FileLogger(File logFile)
{
this.logFile = logFile;
}
public void log(String str)
{
/*
* Logic Append the string
* into the log file.
*/
}
}
LoggerFactory.java. This is the factory class which will create the objects for us. Please note that the objects created depends upon the string loggerType that we pass to the method getLogger. The string is just an example. The condition object can be of any Java object, but we rarely come across such a situation.
public class LoggerFactory
{
public static ILogger getLogger(String loggerType)
{
if(loggerType.equals("console"))
{
return new ConsoleLogger();
}
else if(loggerType.equals("file"))
{
File logFile = new File("Log file path");
return new FileLogger(logFile);
}
else
{
// return console logger by default
return new ConsoleLogger();
}
}
}
LoggerMain.java. This file does not appear in the image above, but this may be any class which uses the objects returned by the factory. Please note that errors and exceptions that may occur are not handled in these examples so that it simplifies the code for us to easily understand.
public class LoggerMain
{
public static void main(String[] args)
{
ILogger logger = LoggerFactory.getLogger(args[0]);
/*
* Use the logger to log stuff
*/
}
}
Usage:
The Factory pattern is used in situations where ,
- The class cannot anticipate which object it needs to create until someone tells it to.
- We need to centralize the details of which class is created.
wow nice!!!
ReplyDelete