本文使用java二十三种设计模式中的工厂方法模式实现简单计算器。
一、项目工程:
二、类图:
三、Calculating类(计算器的父类):
package 工厂方法模式;
public abstract class Calculating {
public double NumberA;
public double NumberB;
public abstract double GetResult();
public void setNumberA(double numberA) {
NumberA = numberA;
}
public void setNumberB(double numberB) {
NumberB = numberB;
}
}
四、Addition类(加法类):
package 工厂方法模式;
public class Addition extends Calculating {
public double GetResult(){
return NumberA+NumberB;
}
}
五、Subtraction类(减法类):
package 工厂方法模式;
public class Subtraction extends Calculating {
public double GetResult(){
return NumberA-NumberB;
}
}
六、Multiplication类(乘法类):
package 工厂方法模式;
public class Multiplication extends Calculating {
@Override
public double GetResult() {
return NumberA*NumberB;
}
}
七、Division(除法类):
package 工厂方法模式;
public class Division extends Calculating {
@Override
public double GetResult() {
if(NumberB !=0){
return NumberA/NumberB;
}
else {
System.out.println("除数需为非零数!!!");
}
return 0;
}
}
八、CalculatingFactory类(工厂类):
package 工厂方法模式;
public abstract class CalculatingFactory{
public abstract Calculating getCalculating(String x);
}
九、AddFactory类(加法工厂类):
package 工厂方法模式;
public class AddFactory extends CalculatingFactory {
public Calculating getCalculating(String X){
return new Addition();
}
}
十、SubFactory类(减法工厂类):
package 工厂方法模式;
public class SubFactory extends CalculatingFactory {
public Calculating getCalculating(String X){
return new Subtraction();
}
}
十一、MultFactory类(乘法工厂类):
package 工厂方法模式;
public class MultFactory extends CalculatingFactory {
public Calculating getCalculating(String X){
return new Multiplication();
}
}
十二、DivFactory类(除法工厂类):
package 工厂方法模式;
public class DivFactory extends CalculatingFactory {
public Calculating getCalculating(String X){
return new Division();
}
}
十三、Client类(客户端):
package 工厂方法模式;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("输入一个数");
double x=scanner.nextInt();
System.out.println("输入符号");
String ope=scanner.next();
System.out.println("再输入一个数");
double y=scanner.nextInt();
CalculatingFactory addFactory= new AddFactory();
CalculatingFactory multFactory= new MultFactory();
CalculatingFactory subFactory= new SubFactory();
CalculatingFactory divFactory= new DivFactory();
Calculating calculating;
switch (ope){
case "+": calculating= addFactory.getCalculating(ope); break;//当输入符号为"+"时创建加法类对象下面以此类推。
case "-": calculating= subFactory.getCalculating(ope); break;
case "*": calculating= multFactory.getCalculating(ope); break;
case "/": calculating= divFactory.getCalculating(ope); break;
default:calculating=null;
}
calculating.setNumberA(x);
calculating.setNumberB(y);
double result =calculating.GetResult();
System.out.println("结果:"+result);
}
}
十四、运行结果:
最后:本文是基于类图实现的代码,所以使用多处继承,故耦合度较高,不适用于实际开发。原创不易,代码仅供参考,如有错误欢迎斧正!