package com.cx.bank.manager; import com.cx.bank.model.MoneyBean; public class ManagerImpl { MoneyBean moneyBean = new MoneyBean(); public double inquiry(){ double money = moneyBean.getMoney(); return money; } public boolean withdrawals(double money){ if(money <= 0 ){ System.out.println("对不起,您的取款金额需大于0元!"); return false; } double leave = moneyBean.getMoney(); if(money > leave){ System.out.println("对不起,您的存款金额不够!"); return false; } moneyBean.setMoney(leave - money); System.out.println("取款成功!"); return true; } public boolean deposit(double money){ if(money <=0 ){ System.out.println("对不起,您的存款金额需大于0元!"); return false; } double leave = moneyBean.getMoney(); moneyBean.setMoney(leave + money); System.out.println("存款成功!"); return true; } public void exitSystem(){ System.out.println("系统已经退出"); System.exit(1); } }用单例模式实现ManagerImpl对象的创建。
时间: 2024-03-15 17:45:05 浏览: 91
UNITY高亮显示插件Highlight Plus 9.2.unitypackage
好的,下面是使用单例模式实现ManagerImpl对象的创建的代码示例:
```
package com.cx.bank.manager;
import com.cx.bank.model.MoneyBean;
public class ManagerImpl {
private static ManagerImpl instance = null; // 单例模式实例
private MoneyBean moneyBean = new MoneyBean();
private ManagerImpl() {} // 私有构造函数
public static ManagerImpl getInstance() {
if (instance == null) {
instance = new ManagerImpl();
}
return instance;
}
public double inquiry() {
double money = moneyBean.getMoney();
return money;
}
public boolean withdrawals(double money) {
if (money <= 0) {
System.out.println("对不起,您的取款金额需大于0元!");
return false;
}
double leave = moneyBean.getMoney();
if (money > leave) {
System.out.println("对不起,您的存款金额不够!");
return false;
}
moneyBean.setMoney(leave - money);
System.out.println("取款成功!");
return true;
}
public boolean deposit(double money) {
if (money <= 0) {
System.out.println("对不起,您的存款金额需大于0元!");
return false;
}
double leave = moneyBean.getMoney();
moneyBean.setMoney(leave + money);
System.out.println("存款成功!");
return true;
}
public void exitSystem() {
System.out.println("系统已经退出");
System.exit(1);
}
}
```
这里的关键在于将构造函数设为私有,这样外部就无法通过new来创建ManagerImpl对象,而是通过静态方法getInstance()来获取单例模式实例。当instance为null时,创建一个新的ManagerImpl对象;当instance不为null时,直接返回该对象。这样就保证了ManagerImpl类只有一个实例对象。
阅读全文