fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. #include <iostream>
  5.  
  6. // Tightly coupled to specific implementations
  7. class Notification {
  8. public:
  9. void sendEmail(const std::string& message) {
  10. std::cout << "Sending Email: " << message << "\n";
  11. }
  12.  
  13. void sendSMS(const std::string& message) {
  14. std::cout << "Sending SMS: " << message << "\n";
  15. }
  16. };
  17.  
  18. //It is not follwing dependency inversion principles because
  19. //The Notification class is directly tied to the sendEmail and sendSMS methods.
  20. //Adding a new notification method (e.g., PushNotification) would require modifying the Notification class.
  21.  
  22. //Lets make this follow DIP
  23.  
  24. // Abstract base class (Abstraction)
  25. class Notifier {
  26. public:
  27. virtual void sendNotification(const std::string& message) const = 0;
  28. virtual ~Notifier() = default;
  29. };
  30.  
  31. // Concrete implementation: Email Notifier
  32. class EmailNotifier : public Notifier {
  33. public:
  34. void sendNotification(const std::string& message) const override {
  35. std::cout << "Sending Email: " << message << "\n";
  36. }
  37. };
  38.  
  39. // Concrete implementation: SMS Notifier
  40. class SMSNotifier : public Notifier {
  41. public:
  42. void sendNotification(const std::string& message) const override {
  43. std::cout << "Sending SMS: " << message << "\n";
  44. }
  45. };
  46.  
  47. // High-level module depends on abstraction (Notifier)
  48. class Notification {
  49. private:
  50. Notifier& notifier; // Dependency is injected via reference
  51. public:
  52. Notification(Notifier& n) : notifier(n) {}
  53.  
  54. void alert(const std::string& message) {
  55. notifier.sendNotification(message);
  56. }
  57. };
  58.  
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
prog.cpp:48:7: error: redefinition of ‘class Notification’
 class Notification {
       ^~~~~~~~~~~~
prog.cpp:7:7: note: previous definition of ‘class Notification’
 class Notification {
       ^~~~~~~~~~~~
stdout
Standard output is empty