4

说到面向对象的设计,你认为给一个对象一个将自己保存到数据库中的功能会破坏类的凝聚力吗?

想象:

Product p = new Product() 
          {
           Name = "Joy Rider", 
           Price = 100, 
           Currency = "USD"
          };

您是否认为将这个产品 p 保存到 DataBase 最好以这种方式完成:

 p.Save();

或以这样的方式:

 ProductServices.SaveProduct(p);

你怎么看?

4

3 回答 3

8

可以将自己保存到数据库中的对象将违反SRP(单一责任原则)。

持久性本身就是一种责任,应该由专门的类来处理。

这将是除了具有 LOW 内聚性之外 - 与持久性有关的成员与那些不使用并且不会在不处理持久性的类的方法中使用的成员没有关系。

于 2010-12-07T15:09:26.300 回答
5

它确实与单一责任原则相冲突。您的示例中 Product 类的目的是表示产品和对该产品的操作。与数据库交互不是类职责的核心部分。

拥有 ProductServices 类可以提高代码的可维护性。假设在数据库中保存对象的逻辑是改变(它可以改变)你想改变你系统中的每个实体类吗?

于 2010-12-07T15:09:45.623 回答
2

In terms of Object Oriented Design only then no there is nothing wrong with the Save method being part of Product. It would actually be the preferred method within the Object Oriented Design world. And from a pure OO perspective you would not want it broken apart because that's more functional than object.

However, if you believe in the Dependency Inversion Principle which says high level modules should not depend upon low level modules; then a Save method would be appropriate but it should take an abstract Connection type as a parameter. This would give you an nice object model which includes a Save method but it would have no knowledge of the type of connection.

于 2010-12-07T15:25:36.587 回答