简单工厂模式实现计算器
计算类代码:
public abstract class Count {
private double a = 0 ;
private double b = 0 ;
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
abstract double GetResult() throws Exception;
}
编写子类,具体的计算方法,继承计算类:
class Countadd extends Count{
@Override
double GetResult() {
// TODO Auto-generated method stub
double result = 0 ;
result = getA() + getB();
return result;
}
}
class Countsub extends Count{
@Override
double GetResult() {
// TODO Auto-generated method stub
double result = 0 ;
result = getA() - getB();
return result;
}
}
这里只给出加法和减法的例子。现在的问题是不知道实例化哪个对象,这里就用到工厂模式,将来如果想增加其他的运算,乘法除法开根平方就很容易了。
编写工厂类:
public class CountFactory {
public static Count createCount(String value){
Count cou = null;
switch (value) {
case "+":
cou = new Countadd();
break;
case "-":
cou = new Countsub();
break;
}
return cou;
}
}
这时只输入符号工厂类会实例化出适合的对象,通过多态,返回父类的方法实现计算结果。
更改时,只需添加方法比如Countsub(乘法类),再添加到工厂类的case中。
main方法:
public class jisuanqi {
@SuppressWarnings("resource")
public static void main(String[] args){
try {
System.out.print("first number:");
Scanner a1 = new Scanner(System.in);
double a = a1.nextDouble();
System.out.print("value:");
Scanner c1 = new Scanner(System.in);
String c = c1.next();
System.out.print("second number:");
Scanner b1 = new Scanner(System.in);
double b = b1.nextDouble();
Count cou;
cou = CountFactory.createCount(c);
cou.setA(a);
cou.setB(b);
System.out.println("result:"+cou.GetResult());
} catch (Exception e) {
System.out.println("error:"+e.getMessage());
}
}
}
笔记:
scanner sc = new scanner(System.in);
String x = sc.nextLine();