Factory method design pattern in java |
Talk to EasyAssistant |
Factory method design pattern in java. .
Factory Method:- |
The Factory Design Pattern or Factory Method Design Pattern
is the creational design pattern. It is used to create Java Object
based on the context/parameter. Normally we create java object by using 'new' operator (e.g. A a = new A()). This is kind of hardcoding in the java functional code. So we want to seperate object creation part from the code where we write business logic. Factory method design pattern can be adopted to achieve it. Factory method design pattern “defines an interface/abstract class for creating an object, but let subclasses decide which class to instantiate(which object to create). The Factory method design pattern lets a class defer instantiation to its subclasses”. This pattern delegates the responsibility of initializing a class from the client to a particular factory class. It has been used / implemented in the following classes of java.util package
|
Example: package test.easycodeforall.factorymethod; public abstract class Employee { public abstract Double getSalary(); } ------------ package test.easycodeforall.factorymethod; public class ContractEmployee extends Employee { @Override public Double getSalary() { return 1000.00; } } ------------ package test.easycodeforall.factorymethod; public class PermanentEmployee extends Employee { @Override public Double getSalary() { return 2000.00; } } ------------ |
package test.easycodeforall.factorymethod; public abstract class EmployeeFactory { public abstract Employee creageEmployeeObj(); } ------------ package test.easycodeforall.factorymethod; public class ContractEmployeeFactory extends EmployeeFactory { @Override public Employee creageEmployeeObj() { return new ContractEmployee(); } } ------------ package test.easycodeforall.factorymethod; public class PermanentEmployeeFactory extends EmployeeFactory { @Override public Employee creageEmployeeObj() { return new PermanentEmployee(); } } ------------ |
package test.easycodeforall.factorymethod; public class ObjectCreator { public static Employee getEmployee(EmployeeFactory factory) { return factory.creageEmployeeObj(); } } |
package test.easycodeforall.factorymethod; public class TestFactoryMethod { public static String DEFAULT_EMPLOYEE_TYPE = "CONTRACTOR"; public static void main(String[] args) { String employeeType = System.getProperty("employeeType"); if (employeeType == null) employeeType = DEFAULT_EMPLOYEE_TYPE; EmployeeFactory factory = null; if ("CONTRACTOR".equals(employeeType)) { factory = new ContractEmployeeFactory(); } else { factory = new PermanentEmployeeFactory(); } Employee emp = ObjectCreator.getEmployee(factory); emp.getSalary(); } } |
Post Your Comment: |