问题
So in the Data transfer Object there should be only setters and getters.. However what about handling also inserting and deleting objects from the Data transfer Object?
public class dto{
setters and getters...
..
..
public void delete(){
CustomreDao.delete(this.ID);
}
}
Would it be against the DAO pattern itself?
Thanks in advance.
回答1:
Ask yourself this: "how hard would it be to update the DAO's delete method?" If you have a lot of DTOs and suddenly need to change the DAO, then that's a lot of work you just created for yourself.
Leave the responsibility of connecting the DTO to the DAO to something else, where you could control the interaction from a single point.
回答2:
This is a design principle in OO languages. According to Single Responsibility Principle every class should have only one responsibility. The responsibility of DTO classes is to store data for transfer purposes. It should not have any behavior like you put in your example.
回答3:
Data transfer objects are just data containers which is used to transport data between layers and tiers .It mainly contains of attributes ,You can even use public attributes without getters and setters .Data transfer objects do not contain any bussiness logic.
DTO does not have any behaviour except for storage and retrieval of its own data (accessors and mutators).
回答4:
I think the answer is yes - this is against the DAO pattern.
The Data Access Object pattern is about encapsulating access to the object storage.
You can even not use Data Transfer Object at all.
What you are talking about - having methods in the business object itself is Active Record pattern which I would prefer.
You can even use both approaches - use CustomerDao as a way to implement data access through database for example, but use ActiveRecord for convenient interface:
customer.save();
anotherCustomer = Customer.find(id);
These methods could use CustomerDao internally.
I believe DTO used by different complicated frameworks, if you can avoid use it - you could go directly without extra DTO layer.
来源:https://stackoverflow.com/questions/17066975/dao-and-data-transfer-object