In implementing hexagonal or clean architecture in C++, it's important to separate your code into different layers. This architecture emphasizes the independence of different components, making it easier to maintain and test. Below is a simplified approach to achieve hexagonal architecture in C++.
// Domain Layer
class User {
public:
User(std::string name) : name(name) {}
std::string getName() const { return name; }
private:
std::string name;
};
// Repository Interface (Ports)
class UserRepository {
public:
virtual ~UserRepository() {}
virtual void save(const User& user) = 0;
virtual User findById(int id) = 0;
};
// Adapter Implementation (Secondary)
class InMemoryUserRepository : public UserRepository {
public:
void save(const User& user) override {
users[user.getId()] = user;
}
User findById(int id) override {
return users[id];
}
private:
std::unordered_map users;
};
// Application Layer
class UserService {
public:
UserService(UserRepository& userRepo) : userRepo(userRepo) {}
void registerUser(std::string name) {
User user(name);
userRepo.save(user);
}
private:
UserRepository& userRepo;
};
// Main Function
int main() {
InMemoryUserRepository repo;
UserService userService(repo);
userService.registerUser("John Doe");
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?