簡體   English   中英

JAVA OOP資金從一個對象轉移到另一個對象

[英]JAVA OOP money transfer from one object to another

我正在努力解決一個建設性問題。

public static void main(String[] args) {
       BankAccount first = new BankAccount();
       BankAccount second = new BankAccount();
       first.addMoney(110.15);
       second.addMoney(1000.5);
       first.transfer(second, 100.0);

public class BankAccount {
public boolean transfer(BankAccount targetAccount, double amount) {
//first account new balance with transaction fees
balance = balance - (amount + (amount * 0.01));
        return false;
    }
}

我的問題是如何在將第一個對象平衡添加到第二個對象平衡的傳輸方法中實現代碼。

BankAccount中的其他方法addMoney和getBalance工作正常。

在OOP世界中,最好嘗試與現實世界中的同行保持盡可能近的距離。 沒有銀行就不會存在銀行帳戶。 沒有銀行服務,您將無法訪問銀行帳戶。 當您從帳戶轉帳時,減少帳戶中金額的不是您自己。 您只需將請求發送到銀行系統以減少帳戶中的金額並將該金額添加到目標帳戶即可。 我寫了一個簡單的例子給你看。 它缺少許多方面,例如安全性,事務處理服務,持久性和許多其他方面,但是它為您展示了一個概覽。

Banking.java (客戶端)

package com.banking.client;

import com.banking.bankingSystem.AccountService;
import com.banking.bankingSystem.Bank;
import com.banking.bankingSystem.BankService;

public class Banking
{

    public static void main(String[] args) throws java.lang.Exception
    {
        BankService bankService = Bank.requestBankService(); //Request bank service (same as you'd go to banks website)
        bankService.register("John", "hero", 100);
        bankService.register("Smith", "superHero", 100);
        try
        {
            AccountService john = bankService.logIn("John", "hero");
            AccountService smith = bankService.logIn("Smith", "superHero");
            System.out.println(john.getName() + " has " + john.getAvailableMoney() + "$");
            System.out.println(smith.getName() + " has " + john.getAvailableMoney() + "$");
            smith.transfer(john.getName(), 50);
            System.out.println(john.getName() + " has " + john.getAvailableMoney() + "$");
            System.out.println(smith.getName() + " has " + smith.getAvailableMoney() + "$");
            //Now lets try to transfer too large amount of money
            john.transfer(smith.getName(), 200);

        } catch (Exception e)
        {
            //In real world banking, manny problems could happen when you use its services.
            //I've put all exceptions in one place. You shouldn't do this in real programs.
            System.err.println("\u001B[31m" + e.getMessage() + "\u001B[00m");
        }


    }
}

Bank.java 銀行系統。 客戶端只能通過接口訪問

package com.banking.bankingSystem;

import java.util.HashMap;
import java.util.Map;

public class Bank implements BankService
{
    private static Map<String, Account> registeredAccounts;

    Bank()
    {
        registeredAccounts = new HashMap<>();
    }

    public static BankService requestBankService()
    {
        return new Bank();
    }

    @Override
    public void register(String name, String password, int initialAmount)
    {
        registeredAccounts.put(name, new Account(name, password, initialAmount));
        System.out.println("User " + name + " registerred succesfully");
    }

    @Override
    public AccountService logIn(String name, String password) throws Exception
    {
        if(!registeredAccounts.containsKey(name)) throw new Exception("Account of " + name + " is not registerred");
        if(registeredAccounts.get(name).verify(name, password))
        {
            System.out.println("User " + name + " logged in succesfully");
            return new LoggedInUser(registeredAccounts.get(name));
        }
        throw new Exception("Wrong credentials");
    }

    private class LoggedInUser implements AccountService
    {
        private Account loggedAcount;

        LoggedInUser(Account account)
        {
            this.loggedAcount = account;
        }


        @Override
        public int withdraw(int amount) throws Exception
        {
            int withdrawedAmount = loggedAcount.withdraw(amount);
            System.out.println("User " + loggedAcount.getName() + "withdrawed " + Integer.toString(withdrawedAmount) + "$");
            return withdrawedAmount;
        }

        @Override
        public boolean transfer(String to, int amount) throws Exception
        {
            if(registeredAccounts.containsKey(to))
            {
                Account transferTo = registeredAccounts.get(to);
                transferTo.addMoney(loggedAcount.withdraw(amount));
                System.out.println("User " + loggedAcount.getName() + " has transferred " + Integer.toString(amount) + "$ to " + transferTo.getName());
                return true;
            }
            throw new Exception("Can't transfer money to " + to + ". Reason: No such user");
        }

        @Override
        public int getAvailableMoney()
        {
            return loggedAcount.availableMoney();
        }

        @Override
        public String getName()
        {
            return loggedAcount.getName();
        }
    }

}

Account.java 此類必須僅對銀行系統可見。 客戶無法直接訪問其帳戶。

package com.banking.bankingSystem;

class Account
{
    private int money;
    private final String name, password;

    Account(String name, String password, int initialSum)
    {
        money = initialSum;
        this.password = password;
        this.name = name;
    }

    int availableMoney()
    {
        return money;
    }

    public int addMoney(int amountToAdd)
    {
        return money += amountToAdd;
    }

    int withdraw(int amountToTake) throws Exception
    {
        if (hasEnaughMoney(amountToTake))
        {
            money -= amountToTake;
            return amountToTake;
        }
        throw new Exception("Account of " + name + " has not enaugh money");

    }

    boolean verify(String name, String password)
    {
        return this.name.equals(name) && this.password.equals(password);
    }

    String getName()
    {
        return name;
    }

    boolean hasEnaughMoney(int amountToTake)
    {
        return money >= amountToTake;
    }
}

AccountService.java 接口,可供客戶端使用。 客戶應通過此界面訪問帳戶類。

package com.banking.bankingSystem;;

public interface AccountService
{
    int withdraw(int amount) throws Exception;
    boolean transfer(String to, int amount) throws Exception;
    int getAvailableMoney();
    String getName();
}

BankService.java 銀行系統應僅通過此接口對客戶可用。

package com.banking.bankingSystem;

public interface BankService
{
    public void register(String name, String password, int initialAmount);
    public AccountService logIn(String name, String password) throws Exception;
}

您已經注意到,客戶端使用抽象(接口)與系統進行交互。 實現類不可訪問。 快樂的編碼:)

public class BankAccount {

private double balance;

public BankAccount() {
    balance = 0;
}

public boolean transfer(double amount) {
    double newBalance = balance - (amount + (amount * 0.01));
    if(newBalance > 0) {
        balance = newBalance;
    }
    return newBalance>0;
}

private void addMoney(double money) {
    balance += money;
}

public static void main(String[] args) {

    BankAccount first = new BankAccount();
    BankAccount second = new BankAccount();
    first.addMoney(110.15);
    second.addMoney(1000.5);

    boolean result = first.transfer(100.0);
    if(result) {
        second.addMoney(100);
    }

}

}

public static void main(String[] args) {
    first.transfer(second, 100.0);
}

public class BankAccount {

     public boolean transfer(BankAccount targetAccount, double amount) {
                if (amount > balance) {
                    return false;
                }
                balance = balance - (amount + (amount * TRANSACTION_FEE));
                return true;
            }
}

第一個帳戶余額已正確扣除,但仍然不知道如何引用第二個帳戶並將該金額添加到對象。

    public class main {

       public static void main(String[] args) {

           BankAccount first = new BankAccount();
           BankAccount second = new BankAccount();

           first.addMoney(1010.0);
           second.addMoney(200.0);

           first.transfer(second, 100.0);
           System.out.println(second.getBalance());
       }
    }

public class BankAccount {

    public static final double TRANSACTION_FEE = 0.01;
    private double balance;

    public double getBalance() {
        return balance;
    }

    public double withdrawMoney(double amount) {
        if (amount > balance) {
            return Double.NaN;
        } else {
            balance = balance - amount; 
        }
        return balance;
    }

    public void addMoney(double amount) {
        balance = balance + amount;
    }

    public boolean transfer(BankAccount targetAccount, double amount) {
        if (amount > balance) {
            return false;
        } else {
            balance = balance - (amount + (amount * TRANSACTION_FEE));
        }
        return false;
    }
}

System.out.println(second.getBalance()); 在此示例中,應打印到控制台正好300。 正如我說的,實現應盡可能少,方法應保持相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM