设计模式实战:银行账户管理系统的设计与实现

时间:2024-11-16 07:49:00
// 账户抽象类 abstract class Account { private double balance; private List<Observer> observers = new ArrayList<>(); public Account(double initialBalance) { this.balance = initialBalance; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; notifyObservers(); } public void addObserver(Observer observer) { observers.add(observer); } public void removeObserver(Observer observer) { observers.remove(observer); } public void notifyObservers() { for (Observer observer : observers) { observer.update("Balance updated: " + balance); } } public void performOperation(OperationStrategy strategy, double amount) { strategy.execute(this, amount); } // 模板方法 public void executeOperation(double amount) { preOperation(); performOperation(createOperationStrategy(), amount); postOperation(); } protected abstract void preOperation(); protected abstract OperationStrategy createOperationStrategy(); protected abstract void postOperation(); } // 储蓄账户类 class SavingsAccount extends Account { public SavingsAccount(double initialBalance) { super(initialBalance); } @Override protected void preOperation() { System.out.println("Savings Account: Pre-operation."); } @Override protected OperationStrategy createOperationStrategy() { return new DepositStrategy(); } @Override protected void postOperation() { System.out.println("Savings Account: Post-operation."); } } // 支票账户类 class CheckingAccount extends Account { public CheckingAccount(double initialBalance) { super(initialBalance); } @Override protected void preOperation() { System.out.println("Checking Account: Pre-operation."); } @Override protected OperationStrategy createOperationStrategy() { return new WithdrawStrategy(); } @Override protected void postOperation() { System.out.println("Checking Account: Post-operation."); } }