Step-by-Step Implementation of Repository Design Pattern in C++

Let’s consider an example of managing products in an online store using the Repository Design Pattern in C++

Problem Statement

Suppose you are developing an e-commerce application that needs to manage products. The application should be able to add new products, retrieve existing products, update product information, and delete products. Instead of directly interacting with the database, we will utilize the Repository Pattern to handle these operations.

Step 1: Define the Product Entity

The Product class defines the attributes of product, such as id, name and price. This serves as the basic data structure representing a product.

C++




// Product entity representing a product
class Product {
public:
    int id;
    std::string name;
    float price;
 
    Product(int id, std::string name, float price) : id(id), name(std::move(name)), price(price) {}
};


In this step, the Product class acts as a blueprint for creating product objects, each having a unique identifier (id), a name, and a price.

Step 2: Create the Repository Interface

The ProductRepository class is an abstract class that declares methods to manage products, such as adding, retrieving, updating, and deleting.

C++




// Interface for the repository
class ProductRepository {
public:
    virtual void addProduct(const Product& product) = 0;
    virtual Product getProductById(int productId) = 0;
    virtual void updateProduct(const Product& product) = 0;
    virtual void deleteProduct(int productId) = 0;
};


In this step, we create a set of rules that any class, intending to work as a repository for products, must follow. These rules specify the exact methods that a real repository class must have. It’s like making a list of instructions that every repository class must follow.

Step 3: Implement a Concrete Repository

The InMemoryProductRepository class is a concrete implementation of the ProductRepository. It uses an in-memory data structure (here, a vector) to manage products.

C++




// Concrete implementation of the repository (in-memory repository)
class InMemoryProductRepository : public ProductRepository {
private:
    std::vector<Product> products;
 
public:
    void addProduct(const Product& product) override {
        products.push_back(product);
    }
 
    Product getProductById(int productId) override {
        for (const auto& product : products) {
            if (product.id == productId) {
                return product;
            }
        }
        return Product(-1, "Not Found", 0.0); // Return a default product if not found
    }
 
    void updateProduct(const Product& updatedProduct) override {
        for (auto& product : products) {
            if (product.id == updatedProduct.id) {
                product = updatedProduct;
                return;
            }
        }
    }
 
    void deleteProduct(int productId) override {
        products.erase(std::remove_if(products.begin(), products.end(),
            [productId](const Product& product) { return product.id == productId; }),
            products.end());
    }
};


This step involves the implementation of the actual methods declared in the ProductRepository interface. In this case, an in-memory data store (vector) is used to store and manage products. It includes functionalities like adding, retrieving, updating, and deleting products.

Step 4: Usage in Main Function

The main function demonstrates the usage of the InMemoryProductRepository by performing various operations on products.

C++




int main() {
    InMemoryProductRepository productRepo;
 
    // Adding products
    productRepo.addProduct(Product(1, "Keyboard", 25.0));
    productRepo.addProduct(Product(2, "Mouse", 15.0));
 
    // Retrieving and updating product
    Product retrievedProduct = productRepo.getProductById(1);
    std::cout << "Retrieved Product: " << retrievedProduct.name << " - $" << retrievedProduct.price << std::endl;
 
    retrievedProduct.price = 30.0;
    productRepo.updateProduct(retrievedProduct);
 
    // Deleting a product
    productRepo.deleteProduct(2);
 
    return 0;
}


The main function serves as an entry point and demonstrates the functionality provided by the InMemoryProductRepository It creates an instance of the repository, adds products, retrieves a product, updates its prices, and deletes a product.

This code implements a simple in-memory repository for demonstration purposes, but in real-world scenario, the repository would likely interact with a database or some other persistent storage.

Repository Design Pattern

In the world of software creation, managing data is a big deal. It’s like organizing your room but in the digital world. The Repository Design Pattern is like a magical closet that helps you keep your data tidy and easy to use.

When you build software, one of the big challenges is how to handle all the data. In the case of a room example, data can be like books, clothes, or toys scattered all over your room, and you need a system to keep things in order. The Repository Design Pattern is that system. It’s like a super organized closet that stores your data and helps you find it when you need it.

But it’s more than just a closet. The Repository Design Pattern is a set of rules and practices that make your software better. It’s like having a superpower in the world of software. It helps you keep your data organized and makes your software flexible, easier to understand, and simpler to test.

Important Topics for the Repository Design Pattern

  • Repository Design Pattern: Simplifying Data Access
  • Repository Design Pattern explained with an example(Library Analogy)
  • Step-by-Step Implementation of Repository Design Pattern in C++
  • Advantages of Repository Design Pattern
  • Disadvantages of Repository Design Pattern
  • Use Cases for Repository Design Pattern
  • Conclusion

Similar Reads

Repository Design Pattern: Simplifying Data Access

Below is the step-by-step explanation of the Repository Design Pattern...

Repository Design Pattern explained with an example(Library Analogy)

The Repository Design Pattern is like a librarian in a library....

Step-by-Step Implementation of Repository Design Pattern in C++

Let’s consider an example of managing products in an online store using the Repository Design Pattern in C++...

Advantages of Repository Design Pattern

...

Disadvantages of Repository Design Pattern

...

Use Cases for Repository Design Pattern

...

Conclusion

...