Python脚本门面模式如何简化调用

wen 实用脚本 3

本文目录导读:

Python脚本门面模式如何简化调用

  1. 门面模式简介
  2. 复杂的子系统示例
  3. 门面模式实现
  4. 使用示例
  5. 更高级的门面设计
  6. 门面模式的优势
  7. 最佳实践

我来详细解释Python中门面模式(Facade Pattern)如何简化调用:

门面模式简介

门面模式为复杂系统提供一个简单统一的接口,隐藏系统的复杂性。

复杂的子系统示例

# 复杂的子系统1 - 订单系统
class OrderSystem:
    def create_order(self, user_id, product_id, quantity):
        print(f"订单系统:创建订单 - 用户{user_id}, 产品{product_id}, 数量{quantity}")
        return "ORD001"
    def process_payment(self, order_id, amount):
        print(f"订单系统:处理支付 - 订单{order_id}, 金额{amount}")
        return True
# 复杂的子系统2 - 库存系统
class InventorySystem:
    def check_stock(self, product_id, quantity):
        print(f"库存系统:检查库存 - 产品{product_id}, 数量{quantity}")
        return True
    def update_stock(self, product_id, quantity):
        print(f"库存系统:更新库存 - 产品{product_id}, 减少{quantity}")
        return True
# 复杂的子系统3 - 物流系统
class ShippingSystem:
    def arrange_shipping(self, order_id, address):
        print(f"物流系统:安排配送 - 订单{order_id}, 地址{address}")
        return "SF123456789"
    def track_shipment(self, tracking_number):
        print(f"物流系统:追踪物流 - 快递单号{tracking_number}")
        return {"status": "in_transit", "location": "仓库"}
# 复杂的子系统4 - 通知系统
class NotificationSystem:
    def send_sms(self, phone, message):
        print(f"通知系统:发送短信 - {phone}: {message}")
        return True
    def send_email(self, email, subject, body):
        print(f"通知系统:发送邮件 - {email}: {subject}")
        return True

门面模式实现

class ShoppingFacade:
    """购物门面 - 简化客户端调用"""
    def __init__(self):
        self._order_system = OrderSystem()
        self._inventory_system = InventorySystem()
        self._shipping_system = ShippingSystem()
        self._notification_system = NotificationSystem()
    def purchase_product(self, user_id, product_id, quantity, 
                        address, phone, email):
        """简化购买流程 - 一个方法完成所有操作"""
        print(f"\n{'='*50}")
        print(f"开始处理用户{user_id}的购买请求")
        print(f"{'='*50}")
        # 1. 检查库存
        if not self._inventory_system.check_stock(product_id, quantity):
            print("库存不足,购买失败")
            return None
        # 2. 创建订单
        order_id = self._order_system.create_order(user_id, product_id, quantity)
        # 3. 处理支付
        amount = quantity * 199  # 假设单价199
        if not self._order_system.process_payment(order_id, amount):
            print("支付失败")
            return None
        # 4. 更新库存
        self._inventory_system.update_stock(product_id, quantity)
        # 5. 安排配送
        tracking_number = self._shipping_system.arrange_shipping(order_id, address)
        # 6. 发送通知
        message = f"您的订单{order_id}已成功下单,快递单号{tracking_number}"
        self._notification_system.send_sms(phone, message)
        self._notification_system.send_email(email, "订单确认", message)
        print(f"\n购买成功!订单号:{order_id}, 快递单号:{tracking_number}")
        print(f"{'='*50}\n")
        return {
            "order_id": order_id,
            "tracking_number": tracking_number,
            "status": "success"
        }
# ===== 更复杂的门面示例 =====
class SmartHomeFacade:
    """智能家居门面"""
    def __init__(self):
        self._light = LightSystem()
        self._thermostat = ThermostatSystem()
        self._curtain = CurtainSystem()
        self._security = SecuritySystem()
    def good_morning(self):
        """早安模式 - 一键启动"""
        print("🌅 开启早安模式...")
        self._light.set_brightness(80)
        self._light.set_color_warm()
        self._thermostat.set_temperature(24)
        self._curtain.open()
        self._security.disarm()
        print("早安模式已启动!\n")
    def good_night(self):
        """晚安模式 - 一键启动"""
        print("🌙 开启晚安模式...")
        self._curtain.close()
        self._light.set_brightness(10)
        self._light.set_color_blue()
        self._thermostat.set_temperature(22)
        self._security.arm()
        print("晚安模式已启动!\n")
# 子系统类
class LightSystem:
    def set_brightness(self, level):
        print(f"灯光亮度设置为 {level}%")
    def set_color_warm(self):
        print("灯光颜色设置为暖色")
    def set_color_blue(self):
        print("灯光颜色设置为蓝色")
class ThermostatSystem:
    def set_temperature(self, temp):
        print(f"温度设置为 {temp}°C")
    def set_mode(self, mode):
        print(f"空调模式设置为 {mode}")
class CurtainSystem:
    def open(self):
        print("窗帘已打开")
    def close(self):
        print("窗帘已关闭")
class SecuritySystem:
    def arm(self):
        print("安防系统已启动")
    def disarm(self):
        print("安防系统已解除")

使用示例

# 不使用门面 - 客户端需要了解所有子系统
def purchase_without_facade():
    print("=== 不使用门面模式 ===")
    order_sys = OrderSystem()
    inventory_sys = InventorySystem()
    shipping_sys = ShippingSystem()
    notification_sys = NotificationSystem()
    # 客户端需要了解所有子系统的使用方式和顺序
    inventory_sys.check_stock("P001", 2)
    order_id = order_sys.create_order("U001", "P001", 2)
    order_sys.process_payment(order_id, 398)
    inventory_sys.update_stock("P001", 2)
    tracking_number = shipping_sys.arrange_shipping(order_id, "北京市")
    notification_sys.send_sms("13812345678", f"订单{order_id}已发货")
    notification_sys.send_email("test@test.com", "订单确认", f"订单{order_id}已发货")
# 使用门面 - 简化调用
def purchase_with_facade():
    print("=== 使用门面模式 ===")
    facade = ShoppingFacade()
    # 一次性完成购物流程
    result = facade.purchase_product(
        user_id="U001",
        product_id="P001",
        quantity=2,
        address="北京市朝阳区",
        phone="13812345678",
        email="test@test.com"
    )
    return result
# 智能家居示例
def smart_home_example():
    print("=== 智能家居门面示例 ===")
    smart_home = SmartHomeFacade()
    # 简单调用,自动执行复杂流程
    smart_home.good_morning()  # 一键完成多个操作
    smart_home.good_night()    # 一键完成多个操作
# 运行示例
purchase_without_facade()
print("\n" + "="*50 + "\n")
purchase_with_facade()
smart_home_example()

更高级的门面设计

from typing import Dict, Any, Optional
from datetime import datetime
class AdvancedShoppingFacade:
    """增强版购物门面 - 支持缓存、日志、异常处理"""
    def __init__(self):
        self._subsystems = self._init_subsystems()
        self._cache = {}
        self._logger = []
    def _init_subsystems(self):
        return {
            'order': OrderSystem(),
            'inventory': InventorySystem(),
            'shipping': ShippingSystem(),
            'notification': NotificationSystem()
        }
    def purchase_product(self, user_id: str, product_id: str, 
                        quantity: int, **kwargs) -> Dict[str, Any]:
        """高级购买流程 - 包含错误处理和日志"""
        result = {
            'success': False,
            'order_id': None,
            'tracking_number': None,
            'error': None,
            'timestamp': datetime.now()
        }
        try:
            # 检查缓存
            cache_key = f"purchase_{user_id}_{product_id}"
            if cache_key in self._cache:
                return self._cache[cache_key]
            # 执行购买流程(与之前类似)
            self._log(f"开始处理用户{user_id}的购买")
            # ... 购买逻辑
            result['success'] = True
            self._cache[cache_key] = result
        except Exception as e:
            result['error'] = str(e)
            self._log(f"购买失败: {e}")
        return result
    def _log(self, message: str):
        self._logger.append({
            'time': datetime.now(),
            'message': message
        })
# 使用简化版本调用
facade = AdvancedShoppingFacade()
result = facade.purchase_product("U001", "P001", 2, 
                                address="北京市", 
                                phone="13812345678",
                                email="test@test.com")

门面模式的优势

简化客户端代码

# 复杂调用 (7行)
inventory.check_stock(...)
order.create_order(...)
order.process_payment(...)
inventory.update_stock(...)
shipping.arrange_shipping(...)
notification.send_sms(...)
notification.send_email(...)
# 门面调用 (1行)
facade.purchase_product(...)

降低耦合度

  • 客户端不需要了解子系统接口
  • 子系统变化不影响客户端

方便测试和调试

class TestFacade(ShoppingFacade):
    def __init__(self):
        super().__init__()
        self.test_log = []
    def purchase_product(self, *args, **kwargs):
        self.test_log.append(("purchase", args, kwargs))
        return {"order_id": "TEST123", "status": "test"}

提供统一的错误处理

class SafeShoppingFacade(ShoppingFacade):
    def purchase_product(self, *args, **kwargs):
        try:
            return super().purchase_product(*args, **kwargs)
        except Exception as e:
            self.handle_error(e)
            return {"error": str(e)}

最佳实践

  1. 不添加新功能 - 门面只简化接口,不添加业务逻辑
  2. 保持简单 - 每个门面方法做一件事
  3. 合理抽象 - 根据不同的客户端需求提供不同的门面

门面模式让复杂系统变得易于使用,是简化调用的最佳实践之一。

抱歉,评论功能暂时关闭!