ManagerImpl业务类:单例模式 inquiry()---查询方法 withdrawals()---取款方法(实现“余额不足”逻辑判断) deposit()---存款方法(实现“存款不能为负”逻辑判断) exitSystem()---退出系统方法
时间: 2024-01-21 12:02:28 浏览: 28
好的,可以的。下面是一个简单的 ManagerImpl 类的单例模式实现:
```
public class ManagerImpl implements Manager {
private static ManagerImpl instance = null;
private double balance;
private ManagerImpl() {
this.balance = 0.0;
}
public static ManagerImpl getInstance() {
if (instance == null) {
instance = new ManagerImpl();
}
return instance;
}
public double inquiry() {
return this.balance;
}
public synchronized void withdrawals(double amount) throws Exception {
if (amount > this.balance) {
throw new Exception("余额不足");
}
this.balance -= amount;
}
public synchronized void deposit(double amount) throws Exception {
if (amount < 0) {
throw new Exception("存款不能为负");
}
this.balance += amount;
}
public void exitSystem() {
instance = null;
}
}
```
在这个实现中,我们使用私有的构造函数和静态的 getInstance() 方法来保证只有一个 ManagerImpl 实例存在。在 inquiry() 方法中,我们直接返回当前余额;在 withdrawals() 方法中,如果取款金额大于当前余额,就抛出一个“余额不足”的异常;在 deposit() 方法中,如果存款金额为负,就抛出一个“存款不能为负”的异常;在 exitSystem() 方法中,我们将 instance 置为 null,从而释放 ManagerImpl 实例占用的资源。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)