十二、结构型(代理模式)

interface BankAccount { void deposit(double amount); void withdraw(double amount); } class RealBankAccount implements BankAccount { private double balance; public RealBankAccount(double balance) { this.balance = balance; } @Override public void deposit(double amount) { balance += amount; System.out.println("存款成功,当前余额: " + balance); } @Override public void withdraw(double amount) { if (balance >= amount) { balance -= amount; System.out.println("取款成功,当前余额: " + balance); } else { System.out.println("余额不足,取款失败"); } } } // 保护代理类 class ProtectionProxy implements BankAccount { private RealBankAccount realBankAccount; private String userRole; public ProtectionProxy(String userRole, double initialBalance) { this.userRole = userRole; realBankAccount = new RealBankAccount(initialBalance); } @Override public void deposit(double amount) { realBankAccount.deposit(amount); } @Override public void withdraw(double amount) { if ("ADMIN".equals(userRole)) { realBankAccount.withdraw(amount); } else { System.out.println("无权限取款"); } } } // 客户端 public class ProtectionProxyClient { public static void main(String[] args) { BankAccount adminAccount = new ProtectionProxy("ADMIN", 1000); adminAccount.withdraw(500); BankAccount userAccount = new ProtectionProxy("USER", 1000); userAccount.withdraw(500); } }
上一篇:学32位MCU需要有51单片机基础吗?


下一篇:强化学习之PPO算法-2. 算法原理