Java simple factory pattern

Posted by adzie on Tue, 22 Feb 2022 12:18:21 +0100

Java simple factory pattern

Bibliography: Dahua design mode, Cheng Jie, Tsinghua University Press

Code link

When we write programs, in order to be easy to modify, we usually use encapsulation, inheritance and polymorphism to reduce the coupling degree of the program.

For example, we need to implement a simple calculator function. The specific function is to pass in two values and an operator to return the calculation result.

1, Abstract class creation

Usually, we will define the main information inside an abstract class, such as output.

public abstract class Operation {
    private double _numberA = 0;
    private double _numberB = 0;

    public double get_numberA() {
        return _numberA;

    public void set_numberA(double _numberA) {
        this._numberA = _numberA;

    public double get_numberB() {
        return _numberB;

    public void set_numberB(double _numberB) {
        this._numberB = _numberB;

    public abstract double getResult() throws Exception;


We define an abstract calculation function to facilitate us to override this operation under different operations.

2, Definition operation

Next, we define various operations, inherit the information of Operation, and overwrite the calculation function g e t R e s u l t ( ) getResult() getResult()

public class OperationAdd extends Operation {
    public double getResult() {
        return get_numberA() + get_numberB();
public class OperationSub extends Operation {
    public double getResult() {
        return get_numberA() - get_numberB();
public class OperationMul extends Operation{
    public double getResult() {
        return get_numberA() * get_numberB();
public class OperationDiv extends Operation{
    public double getResult() throws Exception {
        if(get_numberB() == 0) {
            throw new Exception("Divisor cannot be 0 ");
        return get_numberA() / get_numberB();

In the process of division, we judge whether the divisor is 0 and throw an exception when it is zero.

3, Factory definition

Next, define a simple factory, pass in our operator, judge, and return to the operation class defined in step 2

public class SimpleFactory {
    public static Operation createOperation(String operate) {
        Operation oper = null;
        switch (operate) {
            case "+":
                oper = new OperationAdd();
            case "-":
                oper = new OperationSub();
            case "*":
                oper = new OperationMul();
            case "/":
                oper = new OperationDiv();
        return oper;

4, Calculation function

Define the calculation function, pass in the operands and operators, generate the operation class inside the function with the factory in step 3, and set _$ numberA $and_ n u m b e r B numberB numberB, finally call the calculation function and return, and all functions can be realized.

public static double calculate(double numberA , double numberB, String operate){
        Operation oper;
        oper = SimpleFactory.createOperation(operate);
        try {
            return oper.getResult();
        } catch (Exception e) {
        return 0;

5, Testing

Call in main function c a l c u l a t e ( ) calculate() calculate() function and print

public static void main(String[] args) {
// Operation results
java.lang.Exception: Divisor cannot be 0 
	at OperationDiv.getResult(
	at Calculator.calculate(
	at Calculator.main(


Using the factory mode can reduce the maintenance cost. For example, if we want to add an operation, we only need to inherit our initial abstract class with the new operation, overwrite the calculation function, and add our operation in the factory, which greatly reduces the coupling of our code.

Topics: Java