简单工厂模式

主方法+工厂类

/**
 * Created by king on 2017/7/6.
 */
public class main {
    public static void main(String[] args) {
        Operation oper = OperationFactory.createOperation('*');
        oper.setNumberA(4);
        oper.setNumberB(6);
        double result = oper.getResult();
        System.out.println(result);
    }

    public static class OperationFactory {
        public static Operation createOperation(char operation) {
            Operation oper = null;
            switch (operation) {
                case '+':
                    oper = new OperationAdd();
                    break;
                case '-':
                    oper = new OperationSub();
                    break;
                case '*':
                    oper = new OperationMul();
                    break;
                case '/':
                    oper = new OperationDiv();
                    break;
            }
            return oper;
        }
    }
}

父类

public abstract class Operation {
    private double numberA = 0;
    private double numberB = 0;
    private double result = 0;

    public double getNumberA() {
        return numberA;
    }

    public void setNumberA(double numberA) {
        this.numberA = numberA;
    }

    public double getNumberB() {
        return numberB;
    }

    public void setNumberB(double numberB) {
        this.numberB = numberB;
    }

    public double getResult() {
        return result;
    }

    public void setResult(double result) {
        this.result = result;
    }
}

加减乘除

public class OperationAdd extends Operation {
    @Override
    public double getResult() {
        return super.getNumberA() + super.getNumberB();
    }
}

public class OperationDiv extends Operation {
    @Override
    public double getResult() {
        return super.getNumberA() / super.getNumberB();
    }
}

public class OperationMul extends Operation {
    @Override
    public double getResult() {
        return super.getNumberA() * super.getNumberB();
    }
}

public class OperationSub extends Operation {
    public double getResult() {
        return super.getNumberA() - super.getNumberB();
    }
}

你可能感兴趣的:(简单工厂模式)