第十章:外观模式 - 复杂系统的简化大师
故事延续:统一接口的简洁之道
在Decorator展示完他的装饰艺术后,Facade面如冠玉、气质儒雅地走出,他步履从容,向众人微微颔首。这位气质儒雅的君子声音温和而清晰,给人一种安定和信任感。
"Decorator兄的动态装饰确实灵活,"Facade温和地说道,"但在复杂系统面前,客户端往往需要更简洁的接口。我的武学核心在于------为子系统中的一组接口提供一个一致的界面,定义一个高层接口,使得这一子系统更加容易使用。"
外观模式的武学精要
核心心法
Facade双手轻抚,空中浮现出一座宏伟建筑的门面,背后是错综复杂的结构:"我的十二字真言是------统一入口,简化调用。通过提供一个统一的高层接口,我隐藏了子系统的复杂性,使客户端只需要与这个门面交互,而不需要了解子系统内部的细节。"
C++ 代码实战
cpp
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <map>
// 复杂子系统:家庭影院系统
// 子系统1:投影仪
class Projector {
private:
bool isOn_;
std::string currentSource_;
int brightness_;
public:
Projector() : isOn_(false), brightness_(50) {}
void turnOn() {
isOn_ = true;
std::cout << "📽️ 投影仪已开启" << std::endl;
}
void turnOff() {
isOn_ = false;
std::cout << "📽️ 投影仪已关闭" << std::endl;
}
void setSource(const std::string& source) {
currentSource_ = source;
std::cout << "📽️ 投影仪输入源设置为: " << source << std::endl;
}
void setBrightness(int level) {
brightness_ = level;
std::cout << "📽️ 投影仪亮度设置为: " << level << "%" << std::endl;
}
void adjustFocus() {
std::cout << "📽️ 调整投影仪焦距" << std::endl;
}
bool isOn() const {
return isOn_;
}
};
// 子系统2:音响系统
class SoundSystem {
private:
bool isOn_;
int volume_;
std::string soundMode_;
bool isSurroundEnabled_;
public:
SoundSystem() : isOn_(false), volume_(30), soundMode_("标准"), isSurroundEnabled_(false) {}
void turnOn() {
isOn_ = true;
std::cout << "🔊 音响系统已开启" << std::endl;
}
void turnOff() {
isOn_ = false;
std::cout << "🔊 音响系统已关闭" << std::endl;
}
void setVolume(int level) {
volume_ = level;
std::cout << "🔊 音量设置为: " << level << "%" << std::endl;
}
void setSoundMode(const std::string& mode) {
soundMode_ = mode;
std::cout << "🔊 音效模式设置为: " << mode << std::endl;
}
void enableSurroundSound() {
isSurroundEnabled_ = true;
std::cout << "🔊 环绕声已启用" << std::endl;
}
void disableSurroundSound() {
isSurroundEnabled_ = false;
std::cout << "🔊 环绕声已禁用" << std::endl;
}
bool isOn() const {
return isOn_;
}
};
// 子系统3:蓝光播放器
class BluRayPlayer {
private:
bool isOn_;
bool isPlaying_;
std::string currentMovie_;
public:
BluRayPlayer() : isOn_(false), isPlaying_(false) {}
void turnOn() {
isOn_ = true;
std::cout << "📀 蓝光播放器已开启" << std::endl;
}
void turnOff() {
isOn_ = false;
isPlaying_ = false;
std::cout << "📀 蓝光播放器已关闭" << std::endl;
}
void playMovie(const std::string& movie) {
if (!isOn_) {
std::cout << "❌ 请先开启蓝光播放器" << std::endl;
return;
}
currentMovie_ = movie;
isPlaying_ = true;
std::cout << "🎬 开始播放电影: " << movie << std::endl;
}
void stopMovie() {
isPlaying_ = false;
std::cout << "⏹️ 停止播放电影: " << currentMovie_ << std::endl;
currentMovie_.clear();
}
void pause() {
if (isPlaying_) {
std::cout << "⏸️ 电影已暂停: " << currentMovie_ << std::endl;
}
}
bool isPlaying() const {
return isPlaying_;
}
};
// 子系统4:灯光控制系统
class LightingSystem {
private:
bool mainLightsOn_;
bool ambientLightsOn_;
int mainLightLevel_;
int ambientLightLevel_;
public:
LightingSystem() : mainLightsOn_(true), ambientLightsOn_(false), mainLightLevel_(100), ambientLightLevel_(0) {}
void turnOnMainLights() {
mainLightsOn_ = true;
std::cout << "💡 主灯已开启" << std::endl;
}
void turnOffMainLights() {
mainLightsOn_ = false;
std::cout << "💡 主灯已关闭" << std::endl;
}
void turnOnAmbientLights() {
ambientLightsOn_ = true;
std::cout << "✨ 氛围灯已开启" << std::endl;
}
void turnOffAmbientLights() {
ambientLightsOn_ = false;
std::cout << "✨ 氛围灯已关闭" << std::endl;
}
void setMainLightLevel(int level) {
mainLightLevel_ = level;
std::cout << "💡 主灯亮度设置为: " << level << "%" << std::endl;
}
void setAmbientLightLevel(int level) {
ambientLightLevel_ = level;
std::cout << "✨ 氛围灯亮度设置为: " << level << "%" << std::endl;
}
void setCinemaLighting() {
turnOffMainLights();
turnOnAmbientLights();
setAmbientLightLevel(10);
std::cout << "🎭 影院灯光模式已设置" << std::endl;
}
void setNormalLighting() {
turnOnMainLights();
turnOffAmbientLights();
setMainLightLevel(100);
std::cout << "🏠 正常灯光模式已设置" << std::endl;
}
};
// 子系统5:空调系统
class AirConditioning {
private:
bool isOn_;
int temperature_;
std::string mode_;
int fanSpeed_;
public:
AirConditioning() : isOn_(false), temperature_(22), mode_("自动"), fanSpeed_(2) {}
void turnOn() {
isOn_ = true;
std::cout << "❄️ 空调已开启" << std::endl;
}
void turnOff() {
isOn_ = false;
std::cout << "❄️ 空调已关闭" << std::endl;
}
void setTemperature(int temp) {
temperature_ = temp;
std::cout << "❄️ 温度设置为: " << temp << "°C" << std::endl;
}
void setMode(const std::string& mode) {
mode_ = mode;
std::cout << "❄️ 空调模式设置为: " << mode << std::endl;
}
void setFanSpeed(int speed) {
fanSpeed_ = speed;
std::cout << "❄️ 风扇速度设置为: " << speed << "档" << std::endl;
}
void setComfortMode() {
setTemperature(22);
setMode("自动");
setFanSpeed(2);
std::cout << "😊 舒适模式已设置" << std::endl;
}
};
// 外观类:家庭影院外观
class HomeTheaterFacade {
private:
std::shared_ptr<Projector> projector_;
std::shared_ptr<SoundSystem> soundSystem_;
std::shared_ptr<BluRayPlayer> bluRayPlayer_;
std::shared_ptr<LightingSystem> lightingSystem_;
std::shared_ptr<AirConditioning> airConditioning_;
public:
HomeTheaterFacade(
std::shared_ptr<Projector> projector,
std::shared_ptr<SoundSystem> soundSystem,
std::shared_ptr<BluRayPlayer> bluRayPlayer,
std::shared_ptr<LightingSystem> lightingSystem,
std::shared_ptr<AirConditioning> airConditioning)
: projector_(projector), soundSystem_(soundSystem), bluRayPlayer_(bluRayPlayer),
lightingSystem_(lightingSystem), airConditioning_(airConditioning) {}
// 高级接口:看电影模式
void watchMovie(const std::string& movie) {
std::cout << "\n🎭 准备观看电影: " << movie << std::endl;
std::cout << "========================" << std::endl;
// 1. 开启所有设备
std::cout << "\n1. 开启设备..." << std::endl;
projector_->turnOn();
soundSystem_->turnOn();
bluRayPlayer_->turnOn();
airConditioning_->turnOn();
// 2. 配置设备
std::cout << "\n2. 配置设备..." << std::endl;
projector_->setSource("HDMI");
projector_->setBrightness(80);
projector_->adjustFocus();
soundSystem_->setVolume(60);
soundSystem_->setSoundMode("影院");
soundSystem_->enableSurroundSound();
airConditioning_->setComfortMode();
// 3. 设置灯光
std::cout << "\n3. 设置环境..." << std::endl;
lightingSystem_->setCinemaLighting();
// 4. 开始播放
std::cout << "\n4. 开始播放..." << std::endl;
bluRayPlayer_->playMovie(movie);
std::cout << "\n✅ 电影模式准备完成!享受观影时光!" << std::endl;
}
// 高级接口:结束电影
void endMovie() {
std::cout << "\n🛑 结束观影..." << std::endl;
std::cout << "==================" << std::endl;
bluRayPlayer_->stopMovie();
// 恢复正常灯光
lightingSystem_->setNormalLighting();
std::cout << "\n✅ 观影结束!" << std::endl;
}
// 高级接口:只听音乐模式
void listenToMusic() {
std::cout << "\n🎵 音乐欣赏模式" << std::endl;
std::cout << "================" << std::endl;
soundSystem_->turnOn();
soundSystem_->setVolume(50);
soundSystem_->setSoundMode("音乐");
soundSystem_->enableSurroundSound();
lightingSystem_->setAmbientLightLevel(30);
airConditioning_->setComfortMode();
std::cout << "\n✅ 音乐模式准备完成!" << std::endl;
}
// 高级接口:游戏模式
void playGame() {
std::cout << "\n🎮 游戏模式" << std::endl;
std::cout << "============" << std::endl;
projector_->turnOn();
projector_->setSource("游戏");
projector_->setBrightness(100);
soundSystem_->turnOn();
soundSystem_->setVolume(70);
soundSystem_->setSoundMode("游戏");
lightingSystem_->setMainLightLevel(70);
airConditioning_->setTemperature(20);
airConditioning_->setMode("制冷");
std::cout << "\n✅ 游戏模式准备完成!" << std::endl;
}
// 高级接口:关闭所有设备
void turnOffAll() {
std::cout << "\n🔌 关闭所有设备..." << std::endl;
std::cout << "==================" << std::endl;
if (bluRayPlayer_->isPlaying()) {
bluRayPlayer_->stopMovie();
}
projector_->turnOff();
soundSystem_->turnOff();
bluRayPlayer_->turnOff();
airConditioning_->turnOff();
lightingSystem_->setNormalLighting();
std::cout << "\n✅ 所有设备已关闭!" << std::endl;
}
// 高级接口:快速设置
void quickSetup(const std::string& mode) {
if (mode == "电影") {
watchMovie("默认电影");
} else if (mode == "音乐") {
listenToMusic();
} else if (mode == "游戏") {
playGame();
} else {
std::cout << "❌ 未知模式: " << mode << std::endl;
}
}
// 状态查询
void getStatus() const {
std::cout << "\n📊 家庭影院状态" << std::endl;
std::cout << "================" << std::endl;
std::cout << "投影仪: " << (projector_->isOn() ? "开启" : "关闭") << std::endl;
std::cout << "音响系统: " << (soundSystem_->isOn() ? "开启" : "关闭") << std::endl;
std::cout << "蓝光播放器: " << (bluRayPlayer_->isPlaying() ? "播放中" : "停止") << std::endl;
}
};
UML 武功秘籍图
uses uses uses uses uses Projector -bool isOn_ -string currentSource_ -int brightness_ +turnOn() : void +turnOff() : void +setSource(string) : void +setBrightness(int) : void +adjustFocus() : void +isOn() : bool SoundSystem -bool isOn_ -int volume_ -string soundMode_ -bool isSurroundEnabled_ +turnOn() : void +turnOff() : void +setVolume(int) : void +setSoundMode(string) : void +enableSurroundSound() : void +disableSurroundSound() : void +isOn() : bool BluRayPlayer -bool isOn_ -bool isPlaying_ -string currentMovie_ +turnOn() : void +turnOff() : void +playMovie(string) : void +stopMovie() : void +pause() : void +isPlaying() : bool LightingSystem -bool mainLightsOn_ -bool ambientLightsOn_ -int mainLightLevel_ -int ambientLightLevel_ +turnOnMainLights() : void +turnOffMainLights() : void +turnOnAmbientLights() : void +turnOffAmbientLights() : void +setMainLightLevel(int) : void +setAmbientLightLevel(int) : void +setCinemaLighting() : void +setNormalLighting() : void AirConditioning -bool isOn_ -int temperature_ -string mode_ -int fanSpeed_ +turnOn() : void +turnOff() : void +setTemperature(int) : void +setMode(string) : void +setFanSpeed(int) : void +setComfortMode() : void HomeTheaterFacade -shared_ptr<Projector> projector_ -shared_ptr<SoundSystem> soundSystem_ -shared_ptr<BluRayPlayer> bluRayPlayer_ -shared_ptr<LightingSystem> lightingSystem_ -shared_ptr<AirConditioning> airConditioning_ +watchMovie(string) : void +endMovie() : void +listenToMusic() : void +playGame() : void +turnOffAll() : void +quickSetup(string) : void +getStatus() : void
实战演练:电商订单处理系统
cpp
#include <map>
#include <algorithm>
// 更复杂的外观模式应用:电商订单处理系统
// 子系统1:库存管理
class InventoryManager {
private:
std::map<std::string, int> inventory_;
public:
InventoryManager() {
// 初始化库存
inventory_ = {
{"iPhone14", 50},
{"MacBookPro", 20},
{"AirPods", 100},
{"iPad", 30}
};
}
bool checkStock(const std::string& productId, int quantity) {
auto it = inventory_.find(productId);
if (it != inventory_.end() && it->second >= quantity) {
std::cout << "📦 库存检查: " << productId << " 有足够库存 (" << it->second << "个)" << std::endl;
return true;
}
std::cout << "❌ 库存检查: " << productId << " 库存不足" << std::endl;
return false;
}
void updateStock(const std::string& productId, int quantity) {
auto it = inventory_.find(productId);
if (it != inventory_.end()) {
it->second -= quantity;
std::cout << "📦 更新库存: " << productId << " 减少 " << quantity << "个,剩余 " << it->second << "个" << std::endl;
}
}
void restoreStock(const std::string& productId, int quantity) {
auto it = inventory_.find(productId);
if (it != inventory_.end()) {
it->second += quantity;
std::cout << "📦 恢复库存: " << productId << " 增加 " << quantity << "个,现在 " << it->second << "个" << std::endl;
}
}
void displayInventory() const {
std::cout << "\n📊 当前库存:" << std::endl;
for (const auto& item : inventory_) {
std::cout << " " << item.first << ": " << item.second << "个" << std::endl;
}
}
};
// 子系统2:支付处理
class PaymentProcessor {
private:
double balance_;
public:
PaymentProcessor() : balance_(10000.0) {}
bool processPayment(const std::string& orderId, double amount, const std::string& paymentMethod) {
std::cout << "💳 处理支付: 订单 " << orderId << " 金额 $" << amount << " 方式 " << paymentMethod << std::endl;
// 模拟支付处理
if (amount <= balance_) {
balance_ -= amount;
std::cout << "✅ 支付成功! 余额: $" << balance_ << std::endl;
return true;
} else {
std::cout << "❌ 支付失败: 余额不足" << std::endl;
return false;
}
}
void refundPayment(const std::string& orderId, double amount) {
balance_ += amount;
std::cout << "💳 退款处理: 订单 " << orderId << " 金额 $" << amount << " 已退回" << std::endl;
std::cout << "💰 当前余额: $" << balance_ << std::endl;
}
double getBalance() const {
return balance_;
}
};
// 子系统3:物流配送
class ShippingService {
private:
int nextTrackingId_;
public:
ShippingService() : nextTrackingId_(1000) {}
std::string scheduleDelivery(const std::string& orderId, const std::string& address, const std::vector<std::string>& items) {
std::string trackingId = "TRK" + std::to_string(nextTrackingId_++);
std::cout << "🚚 安排配送: 订单 " << orderId << std::endl;
std::cout << " 地址: " << address << std::endl;
std::cout << " 跟踪号: " << trackingId << std::endl;
std::cout << " 物品: ";
for (const auto& item : items) {
std::cout << item << " ";
}
std::cout << std::endl;
return trackingId;
}
void cancelDelivery(const std::string& trackingId) {
std::cout << "🚚 取消配送: 跟踪号 " << trackingId << std::endl;
}
void updateDeliveryStatus(const std::string& trackingId, const std::string& status) {
std::cout << "🚚 更新配送状态: " << trackingId << " -> " << status << std::endl;
}
};
// 子系统4:邮件通知
class EmailService {
public:
void sendOrderConfirmation(const std::string& email, const std::string& orderId, double amount) {
std::cout << "📧 发送订单确认邮件到: " << email << std::endl;
std::cout << " 订单号: " << orderId << std::endl;
std::cout << " 金额: $" << amount << std::endl;
std::cout << " 内容: 感谢您的订购!我们会尽快处理您的订单。" << std::endl;
}
void sendShippingNotification(const std::string& email, const std::string& orderId, const std::string& trackingId) {
std::cout << "📧 发送发货通知邮件到: " << email << std::endl;
std::cout << " 订单号: " << orderId << std::endl;
std::cout << " 跟踪号: " << trackingId << std::endl;
std::cout << " 内容: 您的订单已发货!您可以使用跟踪号查询物流状态。" << std::endl;
}
void sendCancellationNotification(const std::string& email, const std::string& orderId) {
std::cout << "📧 发送取消通知邮件到: " << email << std::endl;
std::cout << " 订单号: " << orderId << std::endl;
std::cout << " 内容: 您的订单已被取消。如有疑问请联系客服。" << std::endl;
}
};
// 子系统5:订单数据库
class OrderDatabase {
private:
std::map<std::string, std::map<std::string, std::string>> orders_;
int nextOrderId_;
public:
OrderDatabase() : nextOrderId_(1000) {}
std::string createOrder(const std::string& customerEmail, const std::map<std::string, int>& items, double totalAmount) {
std::string orderId = "ORD" + std::to_string(nextOrderId_++);
std::map<std::string, std::string> orderInfo;
orderInfo["customerEmail"] = customerEmail;
orderInfo["status"] = "created";
orderInfo["totalAmount"] = std::to_string(totalAmount);
// 保存商品信息
std::string itemsStr;
for (const auto& item : items) {
itemsStr += item.first + ":" + std::to_string(item.second) + ";";
}
orderInfo["items"] = itemsStr;
orders_[orderId] = orderInfo;
std::cout << "💾 创建订单: " << orderId << " 客户: " << customerEmail << " 金额: $" << totalAmount << std::endl;
return orderId;
}
void updateOrderStatus(const std::string& orderId, const std::string& status) {
auto it = orders_.find(orderId);
if (it != orders_.end()) {
it->second["status"] = status;
std::cout << "💾 更新订单状态: " << orderId << " -> " << status << std::endl;
}
}
std::map<std::string, std::string> getOrder(const std::string& orderId) const {
auto it = orders_.find(orderId);
if (it != orders_.end()) {
return it->second;
}
return {};
}
void displayAllOrders() const {
std::cout << "\n📋 所有订单:" << std::endl;
for (const auto& order : orders_) {
std::cout << " 订单号: " << order.first << " | 状态: " << order.second.at("status")
<< " | 金额: $" << order.second.at("totalAmount") << std::endl;
}
}
};
// 外观类:订单处理外观
class OrderProcessingFacade {
private:
std::shared_ptr<InventoryManager> inventoryManager_;
std::shared_ptr<PaymentProcessor> paymentProcessor_;
std::shared_ptr<ShippingService> shippingService_;
std::shared_ptr<EmailService> emailService_;
std::shared_ptr<OrderDatabase> orderDatabase_;
public:
OrderProcessingFacade(
std::shared_ptr<InventoryManager> inventoryManager,
std::shared_ptr<PaymentProcessor> paymentProcessor,
std::shared_ptr<ShippingService> shippingService,
std::shared_ptr<EmailService> emailService,
std::shared_ptr<OrderDatabase> orderDatabase)
: inventoryManager_(inventoryManager), paymentProcessor_(paymentProcessor),
shippingService_(shippingService), emailService_(emailService), orderDatabase_(orderDatabase) {}
// 高级接口:处理新订单
std::string processNewOrder(const std::string& customerEmail, const std::string& address,
const std::map<std::string, int>& items, const std::string& paymentMethod) {
std::cout << "\n🛒 处理新订单" << std::endl;
std::cout << "==============" << std::endl;
// 1. 检查库存
std::cout << "\n1. 检查库存..." << std::endl;
for (const auto& item : items) {
if (!inventoryManager_->checkStock(item.first, item.second)) {
throw std::runtime_error("库存不足: " + item.first);
}
}
// 2. 计算总金额
double totalAmount = calculateTotalAmount(items);
std::cout << "💰 订单总金额: $" << totalAmount << std::endl;
// 3. 创建订单记录
std::string orderId = orderDatabase_->createOrder(customerEmail, items, totalAmount);
// 4. 处理支付
std::cout << "\n2. 处理支付..." << std::endl;
if (!paymentProcessor_->processPayment(orderId, totalAmount, paymentMethod)) {
orderDatabase_->updateOrderStatus(orderId, "payment_failed");
throw std::runtime_error("支付失败");
}
// 5. 更新库存
std::cout << "\n3. 更新库存..." << std::endl;
for (const auto& item : items) {
inventoryManager_->updateStock(item.first, item.second);
}
// 6. 安排配送
std::cout << "\n4. 安排配送..." << std::endl;
std::vector<std::string> itemNames;
for (const auto& item : items) {
itemNames.push_back(item.first + " x" + std::to_string(item.second));
}
std::string trackingId = shippingService_->scheduleDelivery(orderId, address, itemNames);
// 7. 发送确认邮件
std::cout << "\n5. 发送通知..." << std::endl;
emailService_->sendOrderConfirmation(customerEmail, orderId, totalAmount);
// 8. 更新订单状态
orderDatabase_->updateOrderStatus(orderId, "processing");
std::cout << "\n✅ 订单处理完成! 订单号: " << orderId << " 跟踪号: " << trackingId << std::endl;
return orderId;
}
// 高级接口:取消订单
void cancelOrder(const std::string& orderId) {
std::cout << "\n❌ 取消订单: " << orderId << std::endl;
std::cout << "================" << std::endl;
auto orderInfo = orderDatabase_->getOrder(orderId);
if (orderInfo.empty()) {
std::cout << "❌ 订单不存在: " << orderId << std::endl;
return;
}
// 1. 退款
double amount = std::stod(orderInfo["totalAmount"]);
paymentProcessor_->refundPayment(orderId, amount);
// 2. 恢复库存
std::map<std::string, int> items = parseItems(orderInfo["items"]);
for (const auto& item : items) {
inventoryManager_->restoreStock(item.first, item.second);
}
// 3. 取消配送
// 注意:实际系统中需要根据跟踪号取消
shippingService_->cancelDelivery("TRK" + orderId.substr(3));
// 4. 发送取消通知
emailService_->sendCancellationNotification(orderInfo["customerEmail"], orderId);
// 5. 更新订单状态
orderDatabase_->updateOrderStatus(orderId, "cancelled");
std::cout << "\n✅ 订单取消完成!" << std::endl;
}
// 高级接口:发货处理
void shipOrder(const std::string& orderId) {
std::cout << "\n🚚 处理订单发货: " << orderId << std::endl;
std::cout << "==================" << std::endl;
auto orderInfo = orderDatabase_->getOrder(orderId);
if (orderInfo.empty()) {
std::cout << "❌ 订单不存在: " << orderId << std::endl;
return;
}
// 更新配送状态
shippingService_->updateDeliveryStatus("TRK" + orderId.substr(3), "shipped");
// 发送发货通知
emailService_->sendShippingNotification(orderInfo["customerEmail"], orderId, "TRK" + orderId.substr(3));
// 更新订单状态
orderDatabase_->updateOrderStatus(orderId, "shipped");
std::cout << "\n✅ 订单发货完成!" << std::endl;
}
// 高级接口:获取系统状态
void getSystemStatus() const {
std::cout << "\n📈 系统状态概览" << std::endl;
std::cout << "================" << std::endl;
inventoryManager_->displayInventory();
std::cout << "\n💰 账户余额: $" << paymentProcessor_->getBalance() << std::endl;
orderDatabase_->displayAllOrders();
}
private:
double calculateTotalAmount(const std::map<std::string, int>& items) const {
// 模拟价格计算
std::map<std::string, double> prices = {
{"iPhone14", 999.0},
{"MacBookPro", 1999.0},
{"AirPods", 199.0},
{"iPad", 599.0}
};
double total = 0.0;
for (const auto& item : items) {
auto it = prices.find(item.first);
if (it != prices.end()) {
total += it->second * item.second;
}
}
return total;
}
std::map<std::string, int> parseItems(const std::string& itemsStr) const {
std::map<std::string, int> items;
size_t start = 0;
size_t end = itemsStr.find(';');
while (end != std::string::npos) {
std::string item = itemsStr.substr(start, end - start);
size_t colonPos = item.find(':');
if (colonPos != std::string::npos) {
std::string productId = item.substr(0, colonPos);
int quantity = std::stoi(item.substr(colonPos + 1));
items[productId] = quantity;
}
start = end + 1;
end = itemsStr.find(';', start);
}
return items;
}
};
外观模式的招式解析
招式一:分层外观模式
cpp
// 分层外观:为不同层级的用户提供不同复杂度的接口
class LayeredFacadeSystem {
private:
std::shared_ptr<HomeTheaterFacade> basicFacade_;
std::shared_ptr<OrderProcessingFacade> orderFacade_;
public:
LayeredFacadeSystem() {
// 初始化家庭影院子系统
auto projector = std::make_shared<Projector>();
auto soundSystem = std::make_shared<SoundSystem>();
auto bluRayPlayer = std::make_shared<BluRayPlayer>();
auto lightingSystem = std::make_shared<LightingSystem>();
auto airConditioning = std::make_shared<AirConditioning>();
basicFacade_ = std::make_shared<HomeTheaterFacade>(
projector, soundSystem, bluRayPlayer, lightingSystem, airConditioning);
// 初始化订单处理子系统
auto inventoryManager = std::make_shared<InventoryManager>();
auto paymentProcessor = std::make_shared<PaymentProcessor>();
auto shippingService = std::make_shared<ShippingService>();
auto emailService = std::make_shared<EmailService>();
auto orderDatabase = std::make_shared<OrderDatabase>();
orderFacade_ = std::make_shared<OrderProcessingFacade>(
inventoryManager, paymentProcessor, shippingService, emailService, orderDatabase);
}
// 初级用户接口:极简操作
class SimpleInterface {
private:
std::shared_ptr<LayeredFacadeSystem> parent_;
public:
SimpleInterface(std::shared_ptr<LayeredFacadeSystem> parent) : parent_(parent) {}
void watchMovie() {
parent_->basicFacade_->watchMovie("最新电影");
}
void stopMovie() {
parent_->basicFacade_->endMovie();
}
void orderProduct(const std::string& product, int quantity) {
std::map<std::string, int> items = {{product, quantity}};
try {
parent_->orderFacade_->processNewOrder("customer@example.com", "默认地址", items, "信用卡");
} catch (const std::exception& e) {
std::cout << "❌ 订购失败: " << e.what() << std::endl;
}
}
};
// 高级用户接口:更多控制选项
class AdvancedInterface {
private:
std::shared_ptr<LayeredFacadeSystem> parent_;
public:
AdvancedInterface(std::shared_ptr<LayeredFacadeSystem> parent) : parent_(parent) {}
void customizeMovieExperience(const std::string& movie, int volume, int brightness) {
// 先使用基础功能
parent_->basicFacade_->watchMovie(movie);
// 然后进行自定义调整
// 这里可以访问子系统进行更精细的控制
}
void bulkOrder(const std::map<std::string, int>& items) {
try {
parent_->orderFacade_->processNewOrder("vip@example.com", "VIP地址", items, "企业账户");
} catch (const std::exception& e) {
std::cout << "❌ 批量订购失败: " << e.what() << std::endl;
}
}
void getDetailedStatus() {
parent_->orderFacade_->getSystemStatus();
}
};
// 管理员接口:完整系统控制
class AdminInterface {
private:
std::shared_ptr<LayeredFacadeSystem> parent_;
public:
AdminInterface(std::shared_ptr<LayeredFacadeSystem> parent) : parent_(parent) {}
void systemMaintenance() {
std::cout << "\n🔧 系统维护模式" << std::endl;
std::cout << "===============" << std::endl;
// 可以访问所有子系统进行维护操作
parent_->orderFacade_->getSystemStatus();
// 执行维护任务...
std::cout << "🛠️ 执行数据库优化..." << std::endl;
std::cout << "🛠️ 清理临时文件..." << std::endl;
std::cout << "🛠️ 更新系统配置..." << std::endl;
std::cout << "✅ 系统维护完成!" << std::endl;
}
void emergencyShutdown() {
std::cout << "\n🛑 紧急关闭系统" << std::endl;
parent_->basicFacade_->turnOffAll();
std::cout << "所有子系统已安全关闭!" << std::endl;
}
};
// 获取不同层级的接口
SimpleInterface getSimpleInterface() {
return SimpleInterface(shared_from_this());
}
AdvancedInterface getAdvancedInterface() {
return AdvancedInterface(shared_from_this());
}
AdminInterface getAdminInterface() {
return AdminInterface(shared_from_this());
}
};
招式二:智能外观模式
cpp
// 智能外观:根据上下文自动选择最佳配置
class SmartFacade {
private:
std::shared_ptr<HomeTheaterFacade> homeTheater_;
std::shared_ptr<OrderProcessingFacade> orderProcessor_;
public:
SmartFacade(
std::shared_ptr<HomeTheaterFacade> homeTheater,
std::shared_ptr<OrderProcessingFacade> orderProcessor)
: homeTheater_(homeTheater), orderProcessor_(orderProcessor) {}
// 情景感知模式选择
void smartMovieMode(const std::string& movieType) {
std::cout << "\n🤖 智能电影模式: " << movieType << std::endl;
std::cout << "====================" << std::endl;
if (movieType == "动作片") {
homeTheater_->quickSetup("电影");
// 动作片需要更高的音量和对比度
std::cout << "💥 动作片优化: 增强低音,提高对比度" << std::endl;
} else if (movieType == "文艺片") {
homeTheater_->quickSetup("电影");
// 文艺片需要柔和的灯光和音效
std::cout << "🎨 文艺片优化: 柔和灯光,清晰对白" << std::endl;
} else if (movieType == "恐怖片") {
homeTheater_->quickSetup("电影");
// 恐怖片需要特殊的音效和环境
std::cout << "👻 恐怖片优化: 环绕声效,调暗灯光" << std::endl;
} else {
homeTheater_->quickSetup("电影");
}
}
// 智能订单推荐
void smartOrderRecommendation(const std::string& customerType) {
std::cout << "\n🤖 智能订单推荐: " << customerType << std::endl;
std::cout << "====================" << std::endl;
std::map<std::string, int> recommendedItems;
if (customerType == "学生") {
recommendedItems = {{"iPad", 1}, {"AirPods", 1}};
std::cout << "🎓 学生推荐: iPad + AirPods 组合" << std::endl;
} else if (customerType == "商务人士") {
recommendedItems = {{"MacBookPro", 1}, {"iPhone14", 1}};
std::cout << "💼 商务推荐: MacBook Pro + iPhone 组合" << std::endl;
} else if (customerType == "科技爱好者") {
recommendedItems = {{"iPhone14", 1}, {"iPad", 1}, {"AirPods", 1}};
std::cout << "🚀 科技爱好者推荐: 苹果全家桶" << std::endl;
} else {
recommendedItems = {{"iPhone14", 1}};
std::cout << "😊 默认推荐: iPhone 14" << std::endl;
}
try {
orderProcessor_->processNewOrder(customerType + "@example.com", "智能推荐地址", recommendedItems, "智能支付");
} catch (const std::exception& e) {
std::cout << "❌ 智能推荐失败: " << e.what() << std::endl;
}
}
// 自适应系统优化
void adaptiveOptimization() {
std::cout << "\n🔧 自适应系统优化" << std::endl;
std::cout << "==================" << std::endl;
// 检查系统状态并优化
orderProcessor_->getSystemStatus();
// 基于当前状态进行优化
std::cout << "⚡ 优化系统性能..." << std::endl;
std::cout << "📊 分析使用模式..." << std::endl;
std::cout << "🎯 应用最佳实践..." << std::endl;
std::cout << "✅ 自适应优化完成!" << std::endl;
}
};
完整测试代码
cpp
// 测试外观模式
void testFacadePattern() {
std::cout << "=== 外观模式测试开始 ===" << std::endl;
// 测试家庭影院外观
std::cout << "\n--- 家庭影院外观测试 ---" << std::endl;
// 创建子系统
auto projector = std::make_shared<Projector>();
auto soundSystem = std::make_shared<SoundSystem>();
auto bluRayPlayer = std::make_shared<BluRayPlayer>();
auto lightingSystem = std::make_shared<LightingSystem>();
auto airConditioning = std::make_shared<AirConditioning>();
// 创建外观
auto homeTheater = std::make_shared<HomeTheaterFacade>(
projector, soundSystem, bluRayPlayer, lightingSystem, airConditioning);
// 使用外观的简单接口
std::cout << "\n🎬 测试电影模式..." << std::endl;
homeTheater->watchMovie("阿凡达:水之道");
std::cout << "\n📊 检查系统状态..." << std::endl;
homeTheater->getStatus();
std::cout << "\n🎵 测试音乐模式..." << std::endl;
homeTheater->listenToMusic();
std::cout << "\n🛑 结束测试..." << std::endl;
homeTheater->turnOffAll();
// 测试电商订单处理外观
std::cout << "\n--- 电商订单处理外观测试 ---" << std::endl;
auto inventoryManager = std::make_shared<InventoryManager>();
auto paymentProcessor = std::make_shared<PaymentProcessor>();
auto shippingService = std::make_shared<ShippingService>();
auto emailService = std::make_shared<EmailService>();
auto orderDatabase = std::make_shared<OrderDatabase>();
auto orderProcessor = std::make_shared<OrderProcessingFacade>(
inventoryManager, paymentProcessor, shippingService, emailService, orderDatabase);
// 处理测试订单
std::cout << "\n🛒 处理测试订单..." << std::endl;
std::map<std::string, int> orderItems = {{"iPhone14", 1}, {"AirPods", 2}};
try {
std::string orderId = orderProcessor->processNewOrder(
"test@example.com", "测试地址 123号", orderItems, "信用卡");
std::cout << "\n📦 模拟订单发货..." << std::endl;
orderProcessor->shipOrder(orderId);
std::cout << "\n📊 检查系统状态..." << std::endl;
orderProcessor->getSystemStatus();
} catch (const std::exception& e) {
std::cout << "❌ 订单处理错误: " << e.what() << std::endl;
}
// 测试分层外观
std::cout << "\n--- 分层外观测试 ---" << std::endl;
auto layeredSystem = std::make_shared<LayeredFacadeSystem>();
// 初级用户接口
auto simpleUI = layeredSystem->getSimpleInterface();
std::cout << "\n👶 初级用户操作..." << std::endl;
simpleUI.watchMovie();
simpleUI.orderProduct("iPad", 1);
// 高级用户接口
auto advancedUI = layeredSystem->getAdvancedInterface();
std::cout << "\n👨💼 高级用户操作..." << std::endl;
std::map<std::string, int> bulkItems = {{"MacBookPro", 2}, {"iPhone14", 3}};
advancedUI.bulkOrder(bulkItems);
advancedUI.getDetailedStatus();
// 测试智能外观
std::cout << "\n--- 智能外观测试 ---" << std::endl;
auto smartFacade = std::make_shared<SmartFacade>(homeTheater, orderProcessor);
std::cout << "\n🎭 智能电影模式测试..." << std::endl;
smartFacade->smartMovieMode("动作片");
std::cout << "\n🛒 智能订单推荐测试..." << std::endl;
smartFacade->smartOrderRecommendation("学生");
std::cout << "\n🔧 自适应优化测试..." << std::endl;
smartFacade->adaptiveOptimization();
std::cout << "\n=== 外观模式测试结束 ===" << std::endl;
}
// 实战应用:智能家居控制系统
class SmartHomeControlSystem {
private:
std::shared_ptr<HomeTheaterFacade> homeTheater_;
std::shared_ptr<LayeredFacadeSystem> layeredSystem_;
std::shared_ptr<SmartFacade> smartFacade_;
public:
SmartHomeControlSystem() {
initializeSystems();
}
void initializeSystems() {
// 初始化家庭影院子系统
auto projector = std::make_shared<Projector>();
auto soundSystem = std::make_shared<SoundSystem>();
auto bluRayPlayer = std::make_shared<BluRayPlayer>();
auto lightingSystem = std::make_shared<LightingSystem>();
auto airConditioning = std::make_shared<AirConditioning>();
homeTheater_ = std::make_shared<HomeTheaterFacade>(
projector, soundSystem, bluRayPlayer, lightingSystem, airConditioning);
// 初始化分层系统
layeredSystem_ = std::make_shared<LayeredFacadeSystem>();
// 初始化订单处理子系统(模拟)
auto inventoryManager = std::make_shared<InventoryManager>();
auto paymentProcessor = std::make_shared<PaymentProcessor>();
auto shippingService = std::make_shared<ShippingService>();
auto emailService = std::make_shared<EmailService>();
auto orderDatabase = std::make_shared<OrderDatabase>();
auto orderProcessor = std::make_shared<OrderProcessingFacade>(
inventoryManager, paymentProcessor, shippingService, emailService, orderDatabase);
// 初始化智能外观
smartFacade_ = std::make_shared<SmartFacade>(homeTheater_, orderProcessor);
}
void run() {
std::cout << "\n🏠 智能家居控制系统启动" << std::endl;
std::cout << "========================" << std::endl;
while (true) {
std::cout << "\n请选择操作模式:" << std::endl;
std::cout << "1. 家庭娱乐" << std::endl;
std::cout << "2. 智能购物" << std::endl;
std::cout << "3. 系统状态" << std::endl;
std::cout << "4. 退出" << std::endl;
std::cout << "选择: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
entertainmentMode();
break;
case 2:
shoppingMode();
break;
case 3:
systemStatus();
break;
case 4:
std::cout << "👋 再见!" << std::endl;
return;
default:
std::cout << "❌ 无效选择" << std::endl;
}
}
}
private:
void entertainmentMode() {
std::cout << "\n🎮 家庭娱乐模式" << std::endl;
std::cout << "===============" << std::endl;
std::cout << "请选择娱乐项目:" << std::endl;
std::cout << "1. 智能电影" << std::endl;
std::cout << "2. 音乐欣赏" << std::endl;
std::cout << "3. 游戏模式" << std::endl;
std::cout << "选择: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
{
std::cout << "请输入电影类型 (动作片/文艺片/恐怖片): ";
std::string movieType;
std::cin >> movieType;
smartFacade_->smartMovieMode(movieType);
}
break;
case 2:
homeTheater_->listenToMusic();
break;
case 3:
homeTheater_->playGame();
break;
default:
std::cout << "❌ 无效选择" << std::endl;
}
}
void shoppingMode() {
std::cout << "\n🛒 智能购物模式" << std::endl;
std::cout << "===============" << std::endl;
std::cout << "请选择购物方式:" << std::endl;
std::cout << "1. 智能推荐" << std::endl;
std::cout << "2. 快速订购" << std::endl;
std::cout << "选择: ";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
{
std::cout << "请输入用户类型 (学生/商务人士/科技爱好者): ";
std::string userType;
std::cin >> userType;
smartFacade_->smartOrderRecommendation(userType);
}
break;
case 2:
{
auto simpleUI = layeredSystem_->getSimpleInterface();
std::cout << "请输入产品名称: ";
std::string product;
std::cin >> product;
std::cout << "请输入数量: ";
int quantity;
std::cin >> quantity;
simpleUI.orderProduct(product, quantity);
}
break;
default:
std::cout << "❌ 无效选择" << std::endl;
}
}
void systemStatus() {
std::cout << "\n📊 系统状态" << std::endl;
std::cout << "===========" << std::endl;
homeTheater_->getStatus();
smartFacade_->adaptiveOptimization();
}
};
int main() {
testFacadePattern();
// 运行智能家居控制系统示例
SmartHomeControlSystem smartHome;
smartHome.run();
return 0;
}
外观模式的武学心得
适用场景
- 复杂子系统:需要为复杂的子系统提供一个简单的接口时
- 分层架构:需要构建分层结构的系统,减少层与层之间的依赖时
- 客户端简化:客户端与多个子系统之间存在很多依赖关系时
- 入口统一:需要为子系统提供一个统一的入口点,以便集中管理时
优点
- 简化使用:让客户端使用子系统变得更加简单
- 解耦:将客户端与子系统解耦,提高子系统的独立性和可移植性
- 易于维护:将复杂逻辑封装在外观类中,便于维护和修改
- 层次清晰:为复杂的子系统提供一个清晰的层次结构
缺点
- 不符合开闭原则:增加新的子系统可能需要修改外观类
- 过度封装:可能隐藏了客户端需要的高级功能
- 单点故障:外观类可能成为系统的单点故障
武林高手的点评
Decorator 赞叹道:"Facade 兄的简化之道确实高明!能够如此优雅地隐藏复杂系统的细节,这在构建易用系统时确实无人能及。"
Adapter 也点头称赞:"Facade 兄专注于简化复杂系统的接口,而我更关注接口的兼容转换。我们都在改善系统的可用性,但角度不同。"
Facade 谦虚回应:"诸位过奖了。每个模式都有其适用场景。在需要简化复杂系统接口时,我的外观模式确实能发挥重要作用。但在需要动态扩展功能时,Decorator 兄的方法更加合适。"
下章预告
在Facade展示完他的简化艺术后,Flyweight 身形淡薄如纸、几乎透明地走出,他悄无声息地出现,细声细语地说话。
"Facade 兄的接口简化确实优雅,但在处理大量细粒度对象时,内存效率才是关键。" Flyweight 细声说道,"下一章,我将展示如何通过享元模式极致地节省资源,支持海量对象!"
架构老人满意地点头:"善!内存效率确实是性能优化的关键。下一章,就请 Flyweight 展示他的资源共享之道!"
欲知 Flyweight 如何通过享元模式实现极致的内存优化,且听下回分解!