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 patter
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 }
Customer GetCustomerWithOrder(int orderId);
Customer[] 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.