1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
| from abc import ABC, abstractmethod from typing import Optional, Dict, Type import logging
logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__)
class Notifier(ABC): """通知器抽象基类""" @abstractmethod def send(self, message: str) -> bool: """ 发送消息 :param message: 消息内容 :return: 发送成功返回True,失败返回False """ pass
class EmailNotifier(Notifier): """邮件通知器""" def send(self, message: str) -> bool: try: print(f"[Email系统] 发送邮件内容: {message}") logger.info("邮件发送成功") return True except Exception as e: logger.error(f"邮件发送失败: {str(e)}") return False
class SMSNotifier(Notifier): """短信通知器""" def send(self, message: str) -> bool: try: print(f"[SMS系统] 发送短信内容: {message}") logger.info("短信发送成功") return True except Exception as e: logger.error(f"短信发送失败: {str(e)}") return False
class PushNotifier(Notifier): """APP推送通知器""" def send(self, message: str) -> bool: try: print(f"[Push系统] 发送APP推送内容: {message}") logger.info("APP推送发送成功") return True except Exception as e: logger.error(f"APP推送发送失败: {str(e)}") return False
class NotificationFactory(ABC): """通知工厂抽象基类(结合模板方法模式)""" @abstractmethod def create_notifier(self) -> Notifier: """创建通知器实例(工厂方法)""" pass
def deliver(self, message: str, recipient: Optional[str] = None) -> bool: """ 发送通知的模板方法:定义完整的发送流程 :param message: 消息内容 :param recipient: 接收者(可选) :return: 发送是否成功 """ notifier = self.create_notifier() if not self._validate_message(message): logger.error("消息校验失败:消息内容为空") return False formatted_message = self._format_message(message, recipient) print(f"-> 前置处理: 校验消息内容合法性通过,消息已格式化") try: success = notifier.send(formatted_message) except Exception as e: logger.error(f"发送过程出现异常: {str(e)}") success = False if success: print("-> 后置处理: 发送成功,记录日志") self._log_success(formatted_message, recipient) else: print("-> 后置处理: 发送失败,记录错误日志") self._log_failure(formatted_message, recipient) return success
def _validate_message(self, message: str) -> bool: """校验消息合法性(可被子类重写)""" return bool(message and message.strip())
def _format_message(self, message: str, recipient: Optional[str] = None) -> str: """格式化消息(可被子类重写)""" if recipient: return f"致 {recipient}: {message}" return message
def _log_success(self, message: str, recipient: Optional[str]) -> None: """记录成功日志""" logger.info(f"通知发送成功 | 接收者: {recipient or '未指定'} | 内容: {message[:30]}...")
def _log_failure(self, message: str, recipient: Optional[str]) -> None: """记录失败日志""" logger.error(f"通知发送失败 | 接收者: {recipient or '未指定'} | 内容: {message[:30]}...")
class EmailNotificationFactory(NotificationFactory): """邮件通知工厂""" def create_notifier(self) -> Notifier: return EmailNotifier()
def _format_message(self, message: str, recipient: Optional[str] = None) -> str: """邮件特有的格式化逻辑""" header = "【邮件通知】\n" if recipient: return f"{header}尊敬的{recipient},您好!\n{message}\n\n此邮件为系统自动发送,请勿回复。" return f"{header}{message}\n\n此邮件为系统自动发送,请勿回复。"
class SMSNotificationFactory(NotificationFactory): """短信通知工厂""" def create_notifier(self) -> Notifier: return SMSNotifier()
def _format_message(self, message: str, recipient: Optional[str] = None) -> str: """短信特有的格式化逻辑,控制长度""" prefix = "【短信提醒】" msg = f"{prefix}{message}" return msg[:70] + ("..." if len(msg) > 70 else "")
class PushNotificationFactory(NotificationFactory): """APP推送通知工厂""" def create_notifier(self) -> Notifier: return PushNotifier()
def _format_message(self, message: str, recipient: Optional[str] = None) -> str: """推送特有的格式化逻辑""" return f"📱 {message}"
class NotificationFactoryRegistry: """通知工厂注册中心(简单工厂模式实现)""" _factories: Dict[str, Type[NotificationFactory]] = {}
@classmethod def register(cls, notification_type: str, factory_class: Type[NotificationFactory]) -> None: """注册通知类型""" cls._factories[notification_type.lower()] = factory_class logger.debug(f"已注册通知类型: {notification_type}")
@classmethod def get_factory(cls, notification_type: str) -> NotificationFactory: """根据类型获取工厂实例""" factory_class = cls._factories.get(notification_type.lower()) if not factory_class: raise ValueError(f"不支持的通知类型: {notification_type},支持的类型: {list(cls._factories.keys())}") return factory_class()
@classmethod def send_notification(cls, notification_type: str, message: str, recipient: Optional[str] = None) -> bool: """便捷方法:直接发送通知""" factory = cls.get_factory(notification_type) return factory.deliver(message, recipient)
NotificationFactoryRegistry.register("email", EmailNotificationFactory) NotificationFactoryRegistry.register("sms", SMSNotificationFactory) NotificationFactoryRegistry.register("push", PushNotificationFactory)
if __name__ == "__main__": print("=" * 60) print("--- 测试邮件通知流程 ---") email_factory = EmailNotificationFactory() email_factory.deliver("您的验证码是:1234,5分钟内有效,请勿泄露给他人。", recipient="张三")
print("\n" + "=" * 60) print("--- 测试短信通知流程 ---") sms_factory = SMSNotificationFactory() sms_factory.deliver("您有一条新的快递待取,取件码:A12-3-456,请凭取件码到快递柜领取。", recipient="138‌****‌8888")
print("\n" + "=" * 60) print("--- 测试APP推送通知流程 ---") push_factory = PushNotificationFactory() push_factory.deliver("您关注的商品已降价,快来查看吧!", recipient="用户_12345")
print("\n" + "=" * 60) print("--- 使用注册中心统一发送(推荐方式)---") NotificationFactoryRegistry.send_notification( "email", "您的订单已发货,预计明日送达。", recipient="李四" ) print("\n" + "=" * 60) print("--- 测试异常处理:空消息 ---") NotificationFactoryRegistry.send_notification("sms", "", recipient="139‌****‌9999")
print("\n" + "=" * 60) print("--- 测试异常处理:不支持的类型 ---") try: NotificationFactoryRegistry.send_notification("wechat", "测试消息") except ValueError as e: print(f"预期内的错误: {e}")
|