查询语言在MVC模式中的位置在哪里?

时间:2010-06-13 14:36:38

标签: model-view-controller design-patterns

我假设由于查询语言位于控制器内(通常)它属于该组件,但如果我扮演魔鬼的拥护者,我认为查询语言是在模型的域内执行的,并且与该组件紧密耦合,因此它也可能是其中的一部分。

有人知道答案吗?有直接答案还是技术特定?

1 个答案:

答案 0 :(得分:2)

两者都是实现它的合法方式。问题是您需要向用户公开应用程序的内容和方式。在Patterns Of Enterprise Application Architecture(再次说明,我真的想引用那本书;)他们提供了两种方法来实现Domain Model

  • 在Model中实现所有应用程序逻辑(以及查询语言)。这使得您的域模型非常特定于用例(您不能轻易地重用它,因为它已经有一些应用程序逻辑和对所使用的后端存储的依赖性),但它可能更适合于复杂的域逻辑。
  • 将应用程序逻辑放在另一层(可以是控制器在MVC模式或控制器中直接使用的Service Layer)。这通常会使您的模型对象成为普通的数据容器,您不需要向用户公开整个(可能很复杂的)域模型结构(您可以使界面尽可能简单)。

作为代码示例:

// This can also be your controller
class UserService
{
    void save(User user)
    {
        user.password = md5(user.password)
        // Do the save query like "INSER INTO users"... or some ORM stuff
    }
}

class User
{
    String username;
    String password;

    // The following methods might be added if you put your application logic in the domain model
    void setPassword(String password)
    {
        // Creates a dependency to the hashing algorithm used
        this.password = md5(password)
    }

    void save()
    {
        // This generates a dependency to your backend even though
        // the user object doesn't need to know to which backend it gets saved
        // INSET INTO users
    }
}
相关问题