How to Use Simple Factory Pattern in Java


In this example, we can get the method to implement Simple Factory Pattern in Java.

Source Code

package com.beginner.examples;

interface Operation {
    float compute(float a, float b);
}  
//add
class Add implements Operation {
    @Override
    public float compute(float a, float b) {
        return a + b;
    }
}
//subtract
class Subtract implements Operation {
    @Override
    public float compute(float a, float b) {
        return a - b;
    }
}
// simple factory
class SimpleFactory{

    public static Operation getOperation(int operator){
        switch (operator){
            case 0:
                return new Add();
            case 1:
                return new Subtract();
            default:
                break;
        }
        return null;
    }
}  
  
public class SimpleFactoryExample {  
	public static void main(String[] args) {
		// get detail operation
        Operation o = SimpleFactory.getOperation(0);
        System.out.println(o.compute(10, 7));
    }
} 

Output:

17.0
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments