Factory Pattern is a design pattern to create objects based on the type with the help of Factory class.
Factory Class create and return the object based on the type of request, and Caller class not aware of which class returned, however the created class do the operation based on the requested type.
In this example, we have MathFactory Class, where this class return objects of MathOperation which do the operation of addition, subtraction, multiply and division based on the user request during the object created.
All Factory created objects use a common methods to do the functionality, but it will do the operation of its own based on the request type used while creation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
public class Driver { public static void main(String[] args) { MathOperation addition = MathFactory.getOperatorFactory("add"); MathOperation subtract = MathFactory.getOperatorFactory("sub"); MathOperation multiply = MathFactory.getOperatorFactory("mul"); MathOperation division = MathFactory.getOperatorFactory("div"); System.out.println("Add Result:" + addition.doOperation(10, 5)); System.out.println("Sub Result:" + subtract.doOperation(10, 5)); System.out.println("Mul Result:" + multiply.doOperation(10, 5)); System.out.println("Div Result:" + division.doOperation(10, 5)); } } class MathFactory { public static MathOperation getOperatorFactory(String operationType) { MathOperation mathOperation = null; if(operationType.equalsIgnoreCase("add")) { mathOperation = new Addition(); } if(operationType.equalsIgnoreCase("sub")) { mathOperation = new Subtract(); } if(operationType.equalsIgnoreCase("mul")) { mathOperation = new Multiply(); } if(operationType.equalsIgnoreCase("div")) { mathOperation = new Division(); } return mathOperation; } } abstract class MathOperation { public abstract int doOperation(int x, int y) ; } class Addition extends MathOperation { @Override public int doOperation(int x, int y) { return x+y; } } class Subtract extends MathOperation { @Override public int doOperation(int x, int y) { return x-y; } } class Multiply extends MathOperation { @Override public int doOperation(int x, int y) { return x*y; } } class Division extends MathOperation { @Override public int doOperation(int x, int y) { return x/y; } } |
Result:
1 2 3 4 |
Add Result:15 Sub Result:5 Mul Result:50 Div Result:2 |