SOLID原则练习

设计一个 通知系统,该系统可以通过不同的 通知渠道(例如 电子邮件、短信 和 推送通知)向用户发送通知。系统应满足以下要求:

单一职责原则(SRP):每个类应仅有一个职责。
依赖倒置原则(DIP):高层模块不应依赖于低层模块,二者都应依赖于抽象。
里氏替换原则(LSP):子类应能替换其基类而不改变系统的正确性。
接口隔离原则(ISP):客户端不应依赖它不使用的方法,应将庞大的接口拆分为更小、更专一的接口。

要求
定义必要的接口和类,以实现通过不同渠道发送通知的功能。
使用依赖注入(如构造函数注入)来实现模块之间的解耦。
确保系统易于扩展,例如在不修改现有代码的情况下添加新的通知渠道。
提供一个简单的 main 函数,演示如何使用设计好的系统发送不同类型的通知。

#pragma once
#include <string>
#include <iostream>
#include <memory>
// 单一职责原则(SRP)
class INotifier {
public:
    virtual void send(const std::string& message, const std::string& recipient) = 0;
    virtual ~INotifier() = default;
};

class EmailNotifier : public INotifier {
public:
    void send(const std::string& message, const std::string& recipient) override {
        std::cout << "[Email] To: " << recipient << " | Message: " << message << std::endl;
    }
};

// 单一职责原则(SRP):短信通知实现
class SmsNotifier : public INotifier {
public:
    void send(const std::string& message, const std::string& recipient) override {
        // 这里可以添加真实的短信发送逻辑
        std::cout << "[SMS] To: " << recipient << " | Message: " << message << std::endl;
    }
};

// 单一职责原则(SRP):推送通知实现
class PushNotifier : public INotifier {
public:
    void send(const std::string& message, const std::string& recipient) override {
        // 这里可以添加真实的推送通知发送逻辑
        std::cout << "[Push] To: " << recipient << " | Message: " << message << std::endl;
    }
};

class NotificationService {
private:
    // 依赖倒置原则
    std::shared_ptr<INotifier> notifier;
public:
    // 通过构造函数注入依赖
    NotificationService(std::shared_ptr<INotifier> notifier) : notifier(std::move(notifier)){}

    void notify(const std::string& message, const std::string& recipient) {
        notifier->send(message, recipient);
    }
};

int main() {
    std::shared_ptr<INotifier> emailNotifier = std::make_shared<EmailNotifier>();
    NotificationService emailService(emailNotifier);
    emailService.notify("Welcome to our service!", "alice@example.com");

    // 使用短信通知
    std::shared_ptr<INotifier> smsNotifier = std::make_shared<SmsNotifier>();
    NotificationService smsService(smsNotifier);
    smsService.notify("Your OTP is 123456.", "+1234567890");

    // 使用推送通知
    std::shared_ptr<INotifier> pushNotifier = std::make_shared<PushNotifier>();
    NotificationService pushService(pushNotifier);
    pushService.notify("You have a new message.", "bob_device_token");
    return 0;
}