服务层应该位于模型层之上。因此,模型不应该调用服务。
然而,我面临着我需要的情况,例如:
interface Component {
getResult();
}
class Number implements Component {
private value;
public getResult() {
return value;
}
}
class Addition implements Component {
private component1;
private component2;
public getResult() {
return component1->getResult() + component2->getResult();
}
}
class ConstantFromExternalSource implements Component {
private identifier;
public getResult() {
// call a service for fetching constant identified by identifier
}
}
(伪代码)
在这里,我的模型需要通过服务(无论是否是 Web 服务)访问外部数据源。
在这种情况下我该怎么办?可以调用模型中的服务吗?
如果您建议从模型中移走“getResult”方法并将其放入“ComponentService”中,我会不同意,因为这样我就会失去 OOP 的所有优点(这里我的模型创建了一棵需要递归解析的树) ,所以 OOP 是最好的解决方案)。
您可以通过多种方式实现这一目标。
首先,您可以在单独的接口中提取模型的依赖项,例如:
interface CustomService {
getResult();
}
class ExternalService implments CustomService
{
getResult() { // access web service }
}
然后将该依赖项注入到模型中:
class ConstantFromExternalSource implements Component {
private identifier;
private CustomService service;
ConstantFromExternalSource(CustomService service)
{
this.service = service;
}
public getResult() {
// call a service for fetching constant identified by identifier
return service.getResult();
}
}
实现此目的的另一种方法是使用观察者设计模式 http://en.wikipedia.org/wiki/Observer_pattern并通知更高层的抽象你需要从他们那里得到一些东西。
通过这两种方式,您都可以将模型与服务层的具体实现分离。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)