第一章简单工厂模式
计算器实现
建民哥在大二的时候让我们设计一个口算卡
我第一版的设计模式:(虽然功能实现了,但是啥也不是,一旦有新要求需要大改程序直接作废)
//定制数量
int x;
System.out.println("输入制定数位");
Scanner sc = new Scanner(System.in);
x = sc.nextInt();
//打印多少题
int ans = 10;
//最大值
System.out.println("输入限定每个数的最大值");
int len;
len = sc.nextInt();
int random1;
int j = 0;
int re1 = 0;//记录正确个数
//System.out.println(chark);
while (j <= ans) {
int houhou = 0;
String temp = new String();
for (int i = 0; i < (2 * x) - 1; i++) {
if (i % 2 == 0) {
int p = random.nextInt(len) + 1;
temp += Integer.toString(p);
} else {
switch (random.nextInt(4)) {
case 0:
temp += '+';
break;
case 1:
temp += '-';
break;
case 2:
temp += '*';
break;
case 3:
temp += '/';
break;
}
}
}
if (text(str, temp)) {
str[j] = temp;
j++;
System.out.println(temp);
BigDecimal result1 = new BigDecimal(sc.next());
BigDecimal result = cal(temp);
if (result1.equals(result)) {
System.out.println("√");
re1++;
} else {
System.out.println("×");
}
}
}
System.out.println("正确率:" + String.format("%.2f", (re1 * 0.1) / ans * 10));
}
hhh我居然还找出来我以前的代码了,可以发现我很多问题
1.我命名不规范,虽然有注释,但是只能我看懂
2.把+ - * / 封装成Operation接口,然后直接在类中写出,直接调用接口(这样就可以客户端还有逻辑端分开了)---->这样我就完成了封装,继承,多态
3.我在Number类中写两个参数
public class Number {
private double NumberA;
private double NumberB;
public double getNumberA() {
return NumberA;
}
public void setNumberA(double numberA) {
NumberA = numberA;
}
public double getNumberB() {
return NumberB;
}
public void setNumberB(double numberB) {
NumberB = numberB;
}
}
public interface Opeartion {
public double add(double NumberA,double NumberB);
}
public class OperationImpl implements Opeartion{
@Override
public double add(double NumberA,double NumberB)
{
return NumberA + NumberB;
}
}
然后如何去实例化对象?直接new 这个接口嘛,不是,我们需要一个工厂OperationFactory来管理,你的接口,这样你就可以在客户端直接调用方法就行了
public class OpeartionFactory {(19条消息) 简单工厂模式_weiwenlongll的博客-CSDN博客_简单工厂模式 标签:NumberB,temp,NumberA,int,double,大话,----,设计模式,public From: https://www.cnblogs.com/shuangshuangzi/p/16736386.html
public static double creatOperate(String operate,double NumberA,double NumberB)
{
Opeartion opeartion = new Opeartion();
double res = 0;
switch (operate)
{
case "+":
res = opeartion.add(NumberA, NumberB);
case "-":
res = opeartion.delect(NumberA, NumberB);
case "*":
//opeartion.mul(NumberA,NumberB);
case "/":
//opeartion.division(NumberA,NumberB);
}
return res;
}
}