《大话设计模式》 Java代码2

这篇博客展示了如何使用Java实现基于继承和多态的数学运算操作。通过一个`operationFc`类,根据输入的运算符创建不同的运算子类(如加法、减法、乘法和除法),并进行相应的计算。在`operation`抽象类中定义了运算的基础结构,各个子类覆盖`GetResult`方法以实现特定的运算逻辑。程序通过用户输入接收数字和运算符,然后输出计算结果。
摘要由CSDN通过智能技术生成

继承和多态

import java.util.Scanner;

class operationFc {
	String operator;
	public operationFc(String opt) {
		operator = opt;
	}
	public operation creatOperator(double a, double b) {
		operation op = null;
		switch(operator) {
		case "+" :
			op = new operationAdd(a, b);
			break;
		case "-" :
			op = new operationSub(a, b);
			break;
		case "*" :
			op = new operationMul(a, b);
			break;
		case "/" :
			op = new operationDiv(a, b);
			break;
		}
	return op;
	}
}
public abstract class operation {
	protected double A;
	protected double B;
	
	public operation(double a, double b) {
		this.A = a;
		this.B = b;
	}
	public abstract double GetResult();
	public static void main(String[] args) {	
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入数字A");
		String A = sc.nextLine();
		double a = Double.parseDouble(A);
		System.out.println("请选择运算符号(+、-、*、/):");
		String B = sc.nextLine();
		System.out.println("请输入数字B:");
		String C = sc.nextLine();
		double c = Double.parseDouble(C);
		operationFc p = new operationFc(B);
		operation prtn = p.creatOperator(a, c);
		System.out.println("结果是 " + prtn.GetResult());
	}
}

class operationAdd extends operation {

	public operationAdd(double a, double b) {
		super(a, b);
	}
	public double GetResult() {
		return A + B;
	}
}
class operationSub extends operation {

	public operationSub(double a, double b) {
		super(a, b);
	}
	public double GetResult() {
		return A - B;
	}	
}
class operationMul extends operation {

	public operationMul(double a, double b) {
		super(a, b);
	}
	public double GetResult() {
		return A * B;
	}
}
class operationDiv extends operation {

	public operationDiv(double a, double b) {
		super(a, b);
	}
	public double GetResult() {
		if (B == 0)
			throw new ArithmeticException("输入出错,除数不能为零!");
		else
			return A / B;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值