在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());
}
}
這個示例展示了如何創建一個表示貨幣的類,并實現一些基本的貨幣操作。在實際項目中,你可能需要根據業務需求對該類進行擴展,例如添加貨幣轉換功能、格式化輸出等。