用于管理活动资源的通用模式
1.不用管理模式
1
public
class
BalanceChecker {
2 private BankAccountManager mgr;
3
4 public BalanceChecker() {
5 mgr = new BankAccountManager();
6 }
7
8 public boolean hasEnoughMoney( int bankAccountId, double money) {
9 BankAccount account = mgr.getBankAccount(bankAccountId);
10 return account.getBalance() >= money);
11 }
12 }
2 private BankAccountManager mgr;
3
4 public BalanceChecker() {
5 mgr = new BankAccountManager();
6 }
7
8 public boolean hasEnoughMoney( int bankAccountId, double money) {
9 BankAccount account = mgr.getBankAccount(bankAccountId);
10 return account.getBalance() >= money);
11 }
12 }
实际上只需要一个BankAccountManager,它可以被多个对象和线程重用。可以用静态方法代替:
1
public
boolean
hasEnoughMoney(
int
bankAccountId,
double
money) {
2 BankAccount account = BankAccountManager.getBankAccount(bankAccountId);
3 return account.getBalance() >= money;
4 }
2 BankAccount account = BankAccountManager.getBankAccount(bankAccountId);
3 return account.getBalance() >= money;
4 }
但是这样与BankAccountManager紧密耦合在一起。
2.单例模式(Singleton pattern)
简单例子:
1
public
class
Widget {
2 private static Widget instance = new Widget();
3
4 public static Widget getInstance() {
5 return instance;
6 }
7 private Widget() {
8 }
9 public int doSomething( int x, int y) {
10 return x + y;
11 }
12 }
2 private static Widget instance = new Widget();
3
4 public static Widget getInstance() {
5 return instance;
6 }
7 private Widget() {
8 }
9 public int doSomething( int x, int y) {
10 return x + y;
11 }
12 }
重构后的:
1
public
class
BalanceChecker {
2 private BankAccountManager mgr;
3 public BalanceChecker() {
4 mgr = BankAccountManager.getInstance();
5 }
6 public boolean hasEnoughMoney( int bankAccountId, double money) {
7 BankAccount account = mgr.getBankAccount(bankAccountId);
8 return account.getBalance() >= money);
9 }
10 }
2 private BankAccountManager mgr;
3 public BalanceChecker() {
4 mgr = BankAccountManager.getInstance();
5 }
6 public boolean hasEnoughMoney( int bankAccountId, double money) {
7 BankAccount account = mgr.getBankAccount(bankAccountId);
8 return account.getBalance() >= money);
9 }
10 }
如果需要不同类型的BankAccountManager呢?则不行。仍是紧耦合。
3.工厂模式(Factory pattern)
1
public
class
BalanceChecker {
2 private BankAccountManager mgr;
3 public BalanceChecker() {
4 mgr = BankAccountManagerFactory.getManager();
5 }
6 public boolean hasEnoughMoney( int bankAccountId, double money) {
7 BankAccount account = mgr.getBankAccount(bankAccountId);
8 return account.getBalance() >= money);
9 }
10 }
getManager()返回BankAccountManager接口的一个实现。
2 private BankAccountManager mgr;
3 public BalanceChecker() {
4 mgr = BankAccountManagerFactory.getManager();
5 }
6 public boolean hasEnoughMoney( int bankAccountId, double money) {
7 BankAccount account = mgr.getBankAccount(bankAccountId);
8 return account.getBalance() >= money);
9 }
10 }
3.注册类模式(Registry pattern)
工厂类对解耦代码非常有效,当是当有许多工厂类,处理所有不同的工厂类将难以控制。
此时,可以创建一个称为registry的类,把它作为组件仓库,用来存放所有将要选用的组件。
一个注册类最简单的形式仅仅是键到对象的映射。WebWork的ActionContext就是一个注册类的例子