问题描述
我正在试图了解查询对象设计模式。我不能找到好的和简单的例子。有人可以帮助我了解这种设计模式是什么,以及我们可以实现哪些问题?
谢谢,
Santosh
查询设计模式通常与存储库设计模式结合使用。
让我们以一个例子,然后我会给一个很好的文章阅读。假设我们有一个数据库,我们存储有关客户和订单等信息。
然后我们创建一个初始的仓库,如下所示:
class CustomerRepository(){
Customer GetById(int id){// implementation}
void DeleteCustomer(int id){/ / impl}
void GetCustomerWithOrder(int orderId);
void GetCustomersWithOrdersMoreThan(int numberOfOrders);
}
如您所见,每个查询我们在存储库中创建了一个方法非常好,对于有限数量的查询,但是当我们有很多的问题时,他们开始变得很复杂,很多组合(例如让我的客户购买超过1000,住在纽约,他们的信用额度是小于3000)那么我们最终会得到一大堆方法,甚至更糟糕的是,我们不想发生这种存储库中的查询形式泄露一些业务逻辑。
因此,为了重构,我们将存储库更改为如下所示:
class CustomerRepository() {
/ pre>
Customer [] Get(Query query){// implementation}
void DeleteCustomer(int id){// impl}
}
如您所见,我们正在传递一个以对象形式表示我们的查询的查询对象,而存储库有一个只有回购
现在,如何实现该查询对象以及如何构建它将需要大量的代码,所以在这一点上我将引导你到这个。它是在C#,但你会发现它非常有用,你也可以看看( Java ),由NHibernate用来查看不同但类似的实现。
I am trying to understand the "Query object design pattern". I am not able to find good and simple examples for it. Could someone help me to understand what this design pattern is for and in what problem we can implement this?
Thanks, Santosh
解决方案The Query design pattern is usually used in combination with the Repository design pattern.
Let us go with an example and then I will give a nice article to read. Let's say that we have a database where we store information about our customers and their orders, etc.
Then we create an initial repository like this:
class CustomerRepository() { Customer GetById(int id) { // implementation } void DeleteCustomer(int id) { // impl } void GetCustomerWithOrder(int orderId); void GetCustomersWithOrdersMoreThan(int numberOfOrders); }
As you can see for every query we created a method in the repository which is very fine and well for limited number of queries but when we have a lot of them and they start getting complicated with a lot of combinations (e.g. get me customers with purchases that exceed 1000 and live in New York and their credit limit is less than 3000) then we will end up with a long list of methods and even worse, leaking some business logic in the shape of queries inside the repositories which we don't want to happen.
So to refactor that we change the repository to something like this:
class CustomerRepository() { Customer[] Get(Query query) { // implementation } void DeleteCustomer(int id) { // impl } }
As you can see we are passing a Query Object which represents our query in the form of an object and the repository has one and only repository to execute that query and give us the results back.
Now how implement that query object and how to build it will require a lot of code so at this point i will direct you over to this nice article. It is in C# but you will find it very helpful, also you can look at the Criteria API (Java) which is used by NHibernate to see a different but similar implementation.
这篇关于为什么查询对象设计模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!