在Java中设计货币相关的业务逻辑,首先需要了解货币的基本概念和属性。以下是一个简单的示例,展示了如何创建一个表示货币的类,并实现一些基本的货币操作。
public class Money {
private double amount; // 金额
private String currency; // 货币单位,例如:USD, CNY等
public Money(double amount, String currency) {
this.amount = amount;
this.currency = currency;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
}
public class Money {
// ... 其他代码
// 加法操作
public Money add(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException("Currencies do not match");
}
return new Money(this.amount + other.amount, this.currency);
}
// 减法操作
public Money subtract(Money other) {
if (!this.currency.equals(other.currency)) {
throw new IllegalArgumentException("Currencies do not match");
}
return new Money(this.amount - other.amount, this.currency);
}
// 乘法操作
public Money multiply(double multiplier) {
return new Money(this.amount * multiplier, this.currency);
}
// 除法操作
public Money divide(double divisor) {
if (divisor == 0) {
throw new IllegalArgumentException("Divisor cannot be zero");
}
return new Money(this.amount / divisor, this.currency);
}
}
public class Main {
public static void main(String[] args) {
Money money1 = new Money(10, "USD");
Money money2 = new Money(20, "USD");
Money sum = money1.add(money2);
System.out.println("Sum: " + sum.getAmount() + " " + sum.getCurrency());
Money difference = money1.subtract(money2);
System.out.println("Difference: " + difference.getAmount() + " " + difference.getCurrency());
Money product = money1.multiply(3);
System.out.println("Product: " + product.getAmount() + " " + product.getCurrency());
Money quotient = money1.divide(2);
System.out.println("Quotient: " + quotient.getAmount() + " " + quotient.getCurrency());
}
}
这个示例展示了如何创建一个表示货币的类,并实现一些基本的货币操作。在实际项目中,你可能需要根据业务需求对该类进行扩展,例如添加货币转换功能、格式化输出等。