服务层应该位于模型层之上。因此,模型不应该调用服务。
但是,我面临着需要这样做的情况,例如:
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 }
}
然后将该依赖项注入(inject)到模型中:
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();
}
}
实现此目的的另一种方法是使用 Observer Design Pattern并通知更高级别的抽象您需要从他们那里得到一些东西。
通过这两种方式,您都可以将模型与服务层的具体实现分离。
关于oop - 模型-服务解耦 : what if my model needs a service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13527621/