简单工厂模式

假装没事ソ 提交于 2020-03-14 15:44:25

工厂:使用一个单独的类来做创造各种实例的过程(工厂类)

 

初学者代码毛病:

  1. 命名不规范
  2. 多个if判断导致每个if都要判断,多做无用功
  3. 除0判断,非法输入判断

代码应达到的要求:可维护(方便修改),可复用(能重复使用),可扩展(方便增加功能),灵活性好(方便调整功能,比如执行顺序)

设计模式使得程序更加灵活。

例:项目地址

测试类:

1 public class testMain {
2     public static void main(String[] args) throws Exception {
3         Operation operation;
4         operation = OperationFactory.createOperate("/");
5         operation.numberA = 12;
6         operation.numberB = 3;
7         System.out.println(operation.getResult());
8     }
9 }

工厂类:

 1 public class OperationFactory {
 2     public static Operation createOperate(String operate){
 3         Operation op = null;
 4         switch (operate){
 5             case "+":
 6                 op = new OperationAdd();
 7                 break;
 8             case "-":
 9                 op = new OperationSub();
10                 break;
11             case "*":
12                 op = new OperationMul();
13                 break;
14             case "/":
15                 op = new OperationDiv();
16                 break;
17         }
18         return op;
19     }
20 }

运算类:

public class Operation {
    public double numberA = 0;
    public double numberB = 0;

    public double getResult() throws Exception {
        double result = 0;
        return result;
    }
}

加法类:

public class OperationAdd extends Operation{
    public double getResult(){
        double result = 0;
        result = numberA + numberB;
        return result;
    }
}

减法类:

1 public class OperationSub extends Operation{
2     public double getResult(){
3         double result = 0;
4         result = numberA - numberB;
5         return result;
6     }
7 }

乘法类:

public class OperationMul extends Operation {
    public double getResult(){
        double result = 0;
        result = numberA * numberB;
        return result;
    }
}

 除法类:

public class OperationDiv extends Operation {
    public double getResult() throws Exception {
        double result = 0;
        if (numberB==0){
            throw new Exception("除数不能为0!");
        }
        result = numberA/numberB;
        return result;
    }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!