模型与服务的分离:如果我的模型需要服务怎么办? [英] Model-Service decoupling: what if my model needs a service?

查看:62
本文介绍了模型与服务的分离:如果我的模型需要服务怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

服务"层应该位于模型"层的顶部.因此,模型不应该调用服务.

The Service layer is supposed to be on top of the Model layer. As such, models are not supposed to call services.

但是,我正面临一种需要的情况,例如:

However, I'm facing a situation where I need to, for example:

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服务)访问外部数据源.

Here, my model needs to access an external data source through a Service (webservice or not).

在这种情况下我应该怎么做? 可以在模型中调用服务吗?

How am I supposed to do in this situation? Is it OK to call a service in the model?

如果您建议从模型中删除"getResult"方法,然后将其放入"ComponentService",则我会不同意,因为这样一来,我将失去OOP的所有优势(在这里,我的模型将创建一棵需要进行递归解决,因此OOP是最好的解决方案.

If you suggest to move away the "getResult" method from the model and put it into the "ComponentService", I would disagree because I would then loose all the advantages of OOP (and here my model makes a tree that needs to be recursively resolved, so OOP is the best solution).

推荐答案

您可以通过多种方式实现此目的. 首先,您可以在单独的界面中提取模型的依赖项,例如:

You can achieve this in several ways. First of all you can extract your model's dependency in separate interface like:

interface CustomService {
 getResult();
}

class ExternalService implments CustomService 
{
  getResult() { // access web service }
}

然后将该依赖项注入模型:

And then inject that dependency into the model:

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();
    }
}

另一种实现此目的的方法是使用观察者设计模式并通知更高级别的抽象需要他们的帮助.

Another way to achieve this is to use Observer Design Pattern and notify higher level abstractions that you need something from them.

通过两种方式,您都可以将模型与服务层的具体实现脱钩.

In both ways you can decouple you model from concrete implementation of the service layer.

这篇关于模型与服务的分离:如果我的模型需要服务怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆