StructuralC++verifiedVerified
Facade Pattern in C++
Provides a simplified, unified interface to a complex subsystem, hiding its internal complexity from clients.
How to Implement the Facade Pattern in C++
1Step 1: Complex subsystem classes
class VideoDecoder {
public:
std::string decode(const std::string& file) {
return "decoded:" + file;
}
};
class AudioDecoder {
public:
std::string decode(const std::string& file) {
return "audio:" + file;
}
};
class Renderer {
public:
void render(const std::string& video, const std::string& audio) {
std::cout << "Rendering " << video << " with " << audio << "\n";
}
};2Step 2: Facade simplifies the subsystem
class MediaPlayer {
VideoDecoder video_;
AudioDecoder audio_;
Renderer renderer_;
public:
void play(const std::string& file) {
auto v = video_.decode(file);
auto a = audio_.decode(file);
renderer_.render(v, a);
}
};
int main() {
MediaPlayer player;
player.play("movie.mp4");
}#include <iostream>
#include <string>
#include <memory>
#include <vector>
#include <format>
#include <map>
#include <functional>
#include <stdexcept>
// [step] Complex subsystem: User service
class UserService {
public:
struct User {
std::string id, name, email;
};
User getUser(const std::string& id) {
return {id, "User-" + id, id + "@example.com"};
}
bool validateUser(const std::string& id) {
return !id.empty();
}
};
// [step] Complex subsystem: Inventory service
class InventoryService {
public:
struct Item {
std::string sku;
int quantity;
double price;
};
bool checkStock(const std::string& sku, int qty) {
return qty <= 100;
}
Item getItem(const std::string& sku) {
return {sku, 100, 29.99};
}
void reserveStock(const std::string& sku, int qty) {
std::cout << std::format("Reserved {} of {}\n", qty, sku);
}
};
// [step] Complex subsystem: Payment service
class PaymentService {
public:
struct Receipt {
std::string id;
double amount;
bool success;
};
Receipt processPayment(const std::string& userId, double amount) {
return {"rcpt-" + userId, amount, true};
}
void refundPayment(const std::string& receiptId) {
std::cout << std::format("Refunded {}\n", receiptId);
}
};
// [step] Complex subsystem: Notification service
class NotificationService {
public:
void sendEmail(const std::string& to, const std::string& subject,
const std::string& body) {
std::cout << std::format("Email to {}: {} - {}\n", to, subject, body);
}
};
// [step] Facade: OrderFacade unifies all subsystems
class OrderFacade {
UserService users_;
InventoryService inventory_;
PaymentService payments_;
NotificationService notifications_;
public:
struct OrderResult {
bool success;
std::string orderId;
std::string message;
double total;
};
OrderResult placeOrder(const std::string& userId,
const std::string& sku, int quantity) {
// Step 1: Validate user
if (!users_.validateUser(userId))
return {false, "", "Invalid user", 0};
auto user = users_.getUser(userId);
// Step 2: Check inventory
if (!inventory_.checkStock(sku, quantity))
return {false, "", "Out of stock", 0};
auto item = inventory_.getItem(sku);
double total = item.price * quantity;
// Step 3: Process payment
auto receipt = payments_.processPayment(userId, total);
if (!receipt.success) {
return {false, "", "Payment failed", 0};
}
// Step 4: Reserve stock
inventory_.reserveStock(sku, quantity);
// Step 5: Send confirmation
notifications_.sendEmail(user.email, "Order Confirmed",
std::format("Your order for {} x {} ({:.2f}) is confirmed",
quantity, sku, total));
return {true, receipt.id, "Order placed successfully", total};
}
};
// [step] Client uses only the facade
int main() {
OrderFacade shop;
auto result = shop.placeOrder("user-42", "SKU-001", 3);
std::cout << std::format("\nOrder: success={}, id={}, total={:.2f}\n",
result.success, result.orderId, result.total);
std::cout << "Message: " << result.message << "\n";
}Facade Pattern Architecture
hourglass_empty
Rendering diagram...
lightbulb
Facade Pattern in the Real World
“A hotel concierge is a facade for the city’s complex infrastructure. Instead of you directly calling a taxi company, booking a restaurant, and arranging a museum ticket separately, the concierge handles all of it through a single conversation. The underlying services still exist in their full complexity—you just don’t deal with them directly.”