一个天真且难以测试的方法实现可能看起来像这样
public void getFromDatabaseComputeAndStore(SomeType param) {
Collection<Something> s = dao.retrieveSomethingFromDatabase(param);
Collection<Other> o = dao.retrieveOtherFromDatabase(param);
Result r = null;
<do massive computation, call other methods, figure out what r should be>
<based on s and o>
dao.store(r);
}
通常我会将其重构为类似
public void getFromDatabaseComputeAndStore(SomeType param) {
Computer computer = new Computer();
Collection<Something> s = dao.retrieveFromDatabase(param);
Collection<Other> o = dao.retrieveOtherFromDatabase(param);
computer.setSomething(s);
computer.setOther(o);
computer.execute();
Result r = computer.getResult();
dao.store(r);
}
其中Computer
类是关键。这个类不与数据库或其他外部系统交互并且没有副作用,例如它是纯粹的功能。给定相同的somethings
和others
,result
将始终相同。
所以我的问题是:
- 这是一个有名字的已知模式吗
- 具有以下功能的类的通用名称是什么
Computer
我看过Strategy
、Mediator
和Command
模式,但我觉得它们并不完美。