Я полагаю, что вы пытаетесь использовать шаблон проектирования команд .
Если вы изменили свои классы так, чтобы они выглядели так, вещи могли бы работать немного лучше.
public class Account {
// Please do not use SS for an identifier.
private String identifier;
private String name;
// Money needs to be stored in it's lowest common denominator.
// Which in the united states, is pennies.
private long balance;
public Account(String identifier, String name) {
this.identifier = identifier;
this.name = name;
this.balance = 0L;
}
public String getIdentifier() {
return this.identifier;
}
public String getName() {
return this.name;
}
public long getBalance() {
return balance;
}
public void credit(long amount) {
balance =+ amount;
}
public void debit(long amount) {
balance =- amount;
}
}
Тогда вот ваш CreateAccountCommand. Это немного anemi c, но это нормально.
public class CreateAccountCommand {
private String identifier;
private String name;
public CreateAccount(String identifier, String name) {
// Identifier sould actually be generated by something else.
this.identifier = identifier;
name = name;
}
public Account execute() {
return new Account(identifier, name);
}
}
Вот ваша DepositCommand:
public class DepositCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.credit(amount);
}
}
WithdrawCommand:
public class WithdrawCommand {
private Account account;
private long amount;
public DepositCommand(Account account, long amount) {
this.account = account;
this.amount = amount;
}
public void execute() {
this.account.debit(amount);
}
}
Затем выполните все:
public class Run {
public static void main(String... args) {
CreateAccountCommand createAccountCommand = new CreateAccountCommand("12345678", "First_Name Last_Name");
Account account = createAccountCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Deposit $100.00
DepositCommand depositCommand = new DepositCommand(account, 10000);
depositCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
// Withdraw $75.00
WithdrawCommand withdrawCommand = new WithdrawCommand(account, 7500);
withdrawCommand.execute();
System.out.println(account.getIdentifier());
System.out.println(account.getName());
System.out.println("Your new account balance in pennies: " + account.getBalance());
}
}