我的“processPurchase”方法是否正确地向 Java 中的客户帐户收费?

问题描述 投票:0回答:1

我有一段 Java 代码,用于处理不同类型客户(StudentCustomer、StaffCustomer 和通用客户)的购买行为。每种客户类型都有不同的帐户收费方式。我想确保

processPurchase
方法根据客户类型正确地向帐户收费。这是代码:

public void processPurchase(String customerId, String snackId) throws InvalidPurchaseException, Customer.InvalidCustomerException, Snack.InvalidSnackException, Customer.InsufficientBalanceException {
    Customer customer = getCustomer(customerId);
    Snack snack = getSnack(snackId);
    int price = snack.calculatePrice();
    int finalPrice ;
    if (customer instanceof StudentCustomer studentCustomer) {
        finalPrice = studentCustomer.chargeAccount(price);
    } else if (customer instanceof StaffCustomer staffCustomer) {
        finalPrice = staffCustomer.chargeAccount(price);
    } else {
        finalPrice= customer.chargeAccount(price);
    }

    totalSales += finalPrice;
}

when my main is run it seems like the accounts arent being charged right as, the total sales are too high and the wrong amount of negative accounts are shown
java oop exception methods
1个回答
0
投票

您可以覆盖从每种类型的客户中删除现金的方法,而不是检查每个实例。以下是其工作原理的示例:

public class Customer {
    int balance;

    public Customer(int balance){
        this.balance = balance;
    }

    protected void chargeAccount(int productPrice){
        removeFromBalance(productPrice);
    };

    protected void removeFromBalance(int amount){
        this.balance -= amount;
    }
}

然后创建不同类型的客户并覆盖他们的收费方式:

public class StudentCustomer extends Customer{
    public StudentCustomer(int balance){
        super(balance);
    }

    @Override
    protected void chargeAccount(int productPrice) {
        //example : Student has 5$ reduction in price
        removeFromBalance(productPrice - 5 );
    }
}

这样,你只需要调用 chargeAccount() 方法,而不需要自己检查类的实例:

public class Main {
    public static void main(String[] args) {
        Customer student = new StudentCustomer(100);
        Customer simpleCustomer = new Customer(100);

        int snack_cost = 10;

        student.chargeAccount(snack_cost);
        simpleCustomer.chargeAccount(snack_cost);

        System.out.println("Student balance: " + student.balance);
        System.out.println("Simple Customer balance: " + simpleCustomer.balance);
    }
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.