Complete Guide to C++ Factory Pattern | Encapsulation and Scalability in Object Creation
이 글의 핵심
A complete guide to Factory Pattern. Covers Simple Factory, Factory Method, Abstract Factory, and Auto-Register Factory.
What is the Factory Pattern? Why Do We Need It?
Problem Scenario: Redundant Object Creation Logic and Dependencies
Problem: When client code directly depends on concrete classes, adding new types requires modifying all client code.
// Client code (bad example)
std::unique_ptr<Logger> logger;
if (config == "console") {
logger = std::make_unique<ConsoleLogger>();
} else if (config == "file") {
logger = std::make_unique<FileLogger>();
} else if (config == "network") {
logger = std::make_unique<NetworkLogger>();
}
// Adding a new type requires modifying all clients
Solution: The Factory Pattern encapsulates the object creation logic, allowing clients to depend only on the interface, while the Factory determines the concrete class.
// Factory
class LoggerFactory {
public:
static std::unique_ptr<Logger> create(const std::string& type) {
if (type == "console") return std::make_unique<ConsoleLogger>();
if (type == "file") return std::make_unique<FileLogger>();
if (type == "network") return std::make_unique<NetworkLogger>();
return nullptr;
}
};
// Client code (good example)
auto logger = LoggerFactory::create(config);
logger->log("Hello");
// Adding a new type requires modifying only the Factory
flowchart TD
client["Client"]
factory["LoggerFactory::create(type)"]
console["ConsoleLogger"]
file["FileLogger"]
network["NetworkLogger"]
client --> factory
factory --> console
factory --> file
factory --> network
Table of Contents
- Simple Factory
- Factory Method
- Abstract Factory
- Auto-Register Factory
- Common Errors and Solutions
- Production Patterns
- Complete Example: Plugin System
1. Simple Factory
Basic Structure
#include <memory>
#include <string>
#include <iostream>
class Shape {
public:
virtual void draw() const = 0;
virtual ~Shape() = default;
};
class Circle : public Shape {
public:
void draw() const override {
std::cout << "Drawing Circle\n";
}
};
class Rectangle : public Shape {
public:
void draw() const override {
std::cout << "Drawing Rectangle\n";
}
};
class ShapeFactory {
public:
static std::unique_ptr<Shape> create(const std::string& type) {
if (type == "circle") {
return std::make_unique<Circle>();
} else if (type == "rectangle") {
return std::make_unique<Rectangle>();
}
return nullptr;
}
};
int main() {
auto shape = ShapeFactory::create("circle");
if (shape) {
shape->draw(); // "Drawing Circle"
}
}
2. Factory Method
Extending Factories via Inheritance
#include <memory>
#include <iostream>
class Document {
public:
virtual void open() = 0;
virtual ~Document() = default;
};
class PDFDocument : public Document {
public:
void open() override {
std::cout << "Opening PDF\n";
}
};
class WordDocument : public Document {
public:
void open() override {
std::cout << "Opening Word\n";
}
};
// Creator (Factory Method pattern)
class Application {
public:
virtual std::unique_ptr<Document> createDocument() = 0;
void newDocument() {
auto doc = createDocument();
doc->open();
}
virtual ~Application() = default;
};
class PDFApplication : public Application {
public:
std::unique_ptr<Document> createDocument() override {
return std::make_unique<PDFDocument>();
}
};
class WordApplication : public Application {
public:
std::unique_ptr<Document> createDocument() override {
return std::make_unique<WordDocument>();
}
};
int main() {
std::unique_ptr<Application> app = std::make_unique<PDFApplication>();
app->newDocument(); // "Opening PDF"
}
3. Abstract Factory
Creating Related Object Families
#include <memory>
#include <iostream>
// Product families
class Button {
public:
virtual void render() = 0;
virtual ~Button() = default;
};
class Checkbox {
public:
virtual void render() = 0;
virtual ~Checkbox() = default;
};
// Windows products
class WindowsButton : public Button {
public:
void render() override {
std::cout << "Rendering Windows Button\n";
}
};
class WindowsCheckbox : public Checkbox {
public:
void render() override {
std::cout << "Rendering Windows Checkbox\n";
}
};
// Mac products
class MacButton : public Button {
public:
void render() override {
std::cout << "Rendering Mac Button\n";
}
};
class MacCheckbox : public Checkbox {
public:
void render() override {
std::cout << "Rendering Mac Checkbox\n";
}
};
// Abstract Factory
class GUIFactory {
public:
virtual std::unique_ptr<Button> createButton() = 0;
virtual std::unique_ptr<Checkbox> createCheckbox() = 0;
virtual ~GUIFactory() = default;
};
class WindowsFactory : public GUIFactory {
public:
std::unique_ptr<Button> createButton() override {
return std::make_unique<WindowsButton>();
}
std::unique_ptr<Checkbox> createCheckbox() override {
return std::make_unique<WindowsCheckbox>();
}
};
class MacFactory : public GUIFactory {
public:
std::unique_ptr<Button> createButton() override {
return std::make_unique<MacButton>();
}
std::unique_ptr<Checkbox> createCheckbox() override {
return std::make_unique<MacCheckbox>();
}
};
int main() {
std::unique_ptr<GUIFactory> factory;
#ifdef _WIN32
factory = std::make_unique<WindowsFactory>();
#else
factory = std::make_unique<MacFactory>();
#endif
auto button = factory->createButton();
auto checkbox = factory->createCheckbox();
button->render();
checkbox->render();
}
4. Auto-Register Factory
Automatic Registration Without Macros
#include <memory>
#include <string>
#include <map>
#include <functional>
#include <iostream>
class Product {
public:
virtual void use() = 0;
virtual ~Product() = default;
};
class ProductA : public Product {
public:
void use() override {
std::cout << "Using Product A\n";
}
};
class ProductB : public Product {
public:
void use() override {
std::cout << "Using Product B\n";
}
};
// Auto-register Factory
class ProductFactory {
public:
using Creator = std::function<std::unique_ptr<Product>()>;
static void registerProduct(const std::string& type, Creator creator) {
registry()[type] = creator;
}
static std::unique_ptr<Product> create(const std::string& type) {
auto it = registry().find(type);
if (it != registry().end()) {
return it->second();
}
return nullptr;
}
private:
static std::map<std::string, Creator>& registry() {
static std::map<std::string, Creator> reg;
return reg;
}
};
// Auto-register helper
template<typename T>
class AutoRegister {
public:
AutoRegister(const std::string& type) {
ProductFactory::registerProduct(type, []() {
return std::make_unique<T>();
});
}
};
// Global variables for auto-registration
static AutoRegister<ProductA> registerA("A");
static AutoRegister<ProductB> registerB("B");
int main() {
auto product = ProductFactory::create("A");
if (product) {
product->use(); // "Using Product A"
}
}
5. Common Errors and Solutions
Issue 1: Missing nullptr Handling
Symptom: Crash.
Cause: Factory may return nullptr, but the code doesn’t check for it.
// ❌ Incorrect usage: no nullptr check
auto product = Factory::create("unknown");
product->use(); // Crash: dereferencing nullptr
// ✅ Correct usage: nullptr check
auto product = Factory::create("unknown");
if (product) {
product->use();
} else {
std::cerr << "Unknown product type\n";
}
Issue 2: Memory Leaks
Symptom: Memory leaks.
Cause: Objects created with new are not deleted.
// ❌ Incorrect usage: raw pointer
Product* Factory::create(const std::string& type) {
return new ConcreteProduct(); // Who deletes this?
// ✅ Correct usage: unique_ptr
std::unique_ptr<Product> Factory::create(const std::string& type) {
return std::make_unique<ConcreteProduct>();
}
Issue 3: Lack of Scalability
Symptom: Factory requires modification for every new type.
Cause: Use of if-else chains.
// ❌ Incorrect usage: if-else chain
std::unique_ptr<Product> Factory::create(const std::string& type) {
if (type == "A") return std::make_unique<ProductA>();
if (type == "B") return std::make_unique<ProductB>();
// Adding a new type requires modifying this code
return nullptr;
}
// ✅ Correct usage: registration-based
// Use Auto-Register Factory (see example above)
6. Production Patterns
Pattern 1: Parameterized Factory
#include <memory>
#include <string>
#include <iostream>
class Logger {
public:
virtual void log(const std::string& msg) = 0;
virtual ~Logger() = default;
};
class FileLogger : public Logger {
public:
FileLogger(const std::string& path) : filepath(path) {}
void log(const std::string& msg) override {
std::cout << "[File:" << filepath << "] " << msg << '\n';
}
private:
std::string filepath;
};
class LoggerFactory {
public:
static std::unique_ptr<Logger> createFileLogger(const std::string& path) {
return std::make_unique<FileLogger>(path);
}
};
int main() {
auto logger = LoggerFactory::createFileLogger("/var/log/app.log");
logger->log("Application started");
}
Pattern 2: Singleton Factory
class Factory {
public:
static Factory& instance() {
static Factory inst;
return inst;
}
std::unique_ptr<Product> create(const std::string& type) {
auto it = creators.find(type);
if (it != creators.end()) {
return it->second();
}
return nullptr;
}
void registerCreator(const std::string& type, Creator creator) {
creators[type] = creator;
}
private:
Factory() = default;
std::map<std::string, Creator> creators;
};
7. Complete Example: Plugin System
#include <memory>
#include <string>
#include <map>
#include <functional>
#include <iostream>
class Plugin {
public:
virtual void execute() = 0;
virtual std::string getName() const = 0;
virtual ~Plugin() = default;
};
class PluginFactory {
public:
using Creator = std::function<std::unique_ptr<Plugin>()>;
static PluginFactory& instance() {
static PluginFactory inst;
return inst;
}
void registerPlugin(const std::string& name, Creator creator) {
creators_[name] = creator;
}
std::unique_ptr<Plugin> create(const std::string& name) {
auto it = creators_.find(name);
if (it != creators_.end()) {
return it->second();
}
std::cerr << "Plugin not found: " << name << '\n';
return nullptr;
}
void listPlugins() const {
std::cout << "Available plugins:\n";
for (const auto& [name, _] : creators_) {
std::cout << " - " << name << '\n';
}
}
private:
PluginFactory() = default;
std::map<std::string, Creator> creators_;
};
// Auto-register helper
template<typename T>
class PluginRegistrar {
public:
PluginRegistrar(const std::string& name) {
PluginFactory::instance().registerPlugin(name, []() {
return std::make_unique<T>();
});
}
};
// Plugin implementations
class ImagePlugin : public Plugin {
public:
void execute() override {
std::cout << "Processing image...\n";
}
std::string getName() const override {
return "ImagePlugin";
}
};
class VideoPlugin : public Plugin {
public:
void execute() override {
std::cout << "Processing video...\n";
}
std::string getName() const override {
return "VideoPlugin";
}
};
// Auto-registration
static PluginRegistrar<ImagePlugin> registerImage("image");
static PluginRegistrar<VideoPlugin> registerVideo("video");
int main() {
PluginFactory::instance().listPlugins();
auto plugin = PluginFactory::instance().create("image");
if (plugin) {
std::cout << "Loaded: " << plugin->getName() << '\n';
plugin->execute();
}
}
Output:
Available plugins:
- image
- video
Loaded: ImagePlugin
Processing image...
Summary
| Pattern | Description |
|---|---|
| Simple Factory | Creates objects using static methods |
| Factory Method | Extends factories via inheritance |
| Abstract Factory | Creates related object families |
| Auto-Register Factory | Automatically registers types using global variables |
| Advantages | Encapsulation, scalability, dependency inversion |
| Disadvantages | Increased class count, higher complexity |
The Factory Pattern is a key design pattern that encapsulates object creation logic to improve scalability and maintainability.
FAQ
Q1: When should I use the Factory Pattern?
A: Use it when object creation logic is complex, new types are frequently added, or clients should not depend on concrete classes.
Q2: Simple Factory vs Factory Method?
A: Simple Factory uses static methods for simplicity, while Factory Method allows extension via inheritance.
Q3: When should I use Abstract Factory?
A: Use it when you need to create related object families (e.g., Windows UI vs Mac UI).
Q4: What are the advantages of Auto-Register Factory?
A: Adding new types does not require modifying the Factory, as types are automatically registered via global variables.
Q5: What are the disadvantages?
A: Increased class count and higher complexity due to indirect references.
Q6: Where can I learn more about the Factory Pattern?
A:
- “Design Patterns” by Gang of Four
- “Head First Design Patterns” by Freeman & Freeman
- Refactoring Guru: Factory Pattern
One-liner summary: The Factory Pattern encapsulates object creation logic and enhances scalability. Next, check out Observer Pattern for more design patterns.
## 같이 보면 좋은 글 (내부 링크)
이 주제와 연결되는 다른 글입니다.
- [C++ 가상 함수 | "Virtual Functions" 가이드](/blog/cpp-virtual-functions/)
- [C++ 스마트 포인터 | unique_ptr/shared_ptr "메모리 안전" 가이드](/blog/cpp-smart-pointers/)
- [C++ Observer Pattern 완벽 가이드 | 이벤트 기반 아키텍처와 신호/슬롯](/blog/cpp-observer-pattern/)
---
---
## 이 글에서 다루는 키워드 (관련 검색어)
C++, factory, pattern, creational, design, polymorphism 등으로 검색하시면 이 글이 도움이 됩니다.