Wednesday, May 25, 2016

Which Design Pattern should be used instead of using Traditional Constructor and why?

Replace Constructor with Factory Method Pattern.Why lets take a case 

 Suppose you have class like

class Employee { Employee(int type) { this.type = type; } //... }

A complex constructor that does something more than just setting parameter values in object fields.

Solution:
class Employee {
  static Employee create(int type) {
    employee = new Employee(type);
    // do some heavy lifting.
    return employee;
  }
  //...
}

when to use Factory Method Pattern:

- when a class cant guess the type of object it supposed to create.
-when a class wants its subclass to be the ones to specific the type of a newly created object.
-when we want to localize the knowledge of which class gets created.

Example:
public interface AppLogger{
public void log(String logMsg);
}

public class FileLogger implements AppLogger
{
  public void log(String logMsg)
 {
    FileUtil futil=new FileUtil();
    futil.writeTOFile("Logging.txt",logMsg,true,true);
 }
}

public class DatabaseLogger implements AppLogger
{
  public void log(String logMsg)
 {
    // open database connection
    // write log to it.
 }
}
public class ConsoleLogger implements AppLogger
{
  public void log(String logMsg)
 {
     System.out.println("Console" + logMsg);
 }
}

public class LoggerFactory
{
  public Logger  getLogger(int value)
 {
   if(value==1){  return new FileLogger();}
   else if(value==2){ return new DatabaseLogger();}
   elseif(value == 3){ return new ConsoleLogger();}
 }
}

public class LoggerFactoryTest{
  public static void main(String args[])
  {
    LoggerFacrory factory=new LoggerFactory();
    AppLogger logger=factory.getLogger(1);
    logger.log("Message to file");
    logger=factory.getLogger(2);
   logger.log("Message to Database");
   }
}

No comments: