汇总目录请点击访问:《设计模式目录汇总》 喜欢内容的话欢迎关注、点赞、收藏!感谢支持,祝大家祉猷并茂,顺遂无虞!
简单工厂模式(Simple Factory Pattern)是一种创建型设计模式,用于创建对象的实例。通过一个工厂类来决定实例化哪一个具体类,降低客户端与具体类之间的耦合。
对于长switch或者长if、else,且多处调用情形,可以考虑使用简单工厂模式。
#include <iostream>
#include <string>
#include <memory>
// 产品基类
class Product {
public:
virtual void use() = 0;
virtual ~Product() {}
};
// 具体产品 A
class ProductA : public Product {
public:
void use() override {
std::cout << "Using Product A" << std::endl;
}
};
// 具体产品 B
class ProductB : public Product {
public:
void use() override {
std::cout << "Using Product B" << std::endl;
}
};
// 工厂类
class SimpleFactory {
public:
static std::unique_ptr<Product> createProduct(const std::string& type) {
if (type == "A") {
return std::make_unique<ProductA>();
} else if (type == "B") {
return std::make_unique<ProductB>();
} else {
return nullptr;
}
}
};
// 客户端代码
int main() {
auto product = SimpleFactory::createProduct("A");
if (product) {
product->use();
}
return 0;
}using System;
// 产品基类
public abstract class Product {
public abstract void Use();
}
// 具体产品 A
public class ProductA : Product {
public override void Use() {
Console.WriteLine("Using Product A");
}
}
// 具体产品 B
public class ProductB : Product {
public override void Use() {
Console.WriteLine("Using Product B");
}
}
// 工厂类
public class SimpleFactory {
public static Product CreateProduct(string type) {
return type switch {
"A" => new ProductA(),
"B" => new ProductB(),
_ => null
};
}
}
// 客户端代码
class Program {
static void Main(string[] args) {
Product product = SimpleFactory.CreateProduct("A");
product?.Use();
}
}
简单工厂模式是较早被提出的创建型设计模式,虽然不属于 GoF 设计模式,但经常被当作一种基础设计手法,并作为引入工厂方法模式的过渡。以下是一些补充内容:
结合单例模式:将工厂类设计为单例,避免频繁创建工厂实例。
public class SimpleFactory {
private static readonly SimpleFactory instance = new SimpleFactory();
private SimpleFactory() {}
public static SimpleFactory Instance => instance;
public Product CreateProduct(string type) {
return type switch {
"A" => new ProductA(),
"B" => new ProductB(),
_ => null
};
}
}结合配置文件或枚举:将产品类型和具体类之间的映射关系配置到文件或用枚举维护,提高灵活性。
示例:通过映射关系动态加载产品:
Dictionary<string, Func<Product>> productMap = new() {
{ "A", () => new ProductA() },
{ "B", () => new ProductB() }
};
public Product CreateProduct(string type) {
return productMap.TryGetValue(type, out var factory) ? factory() : null;
}动态加载类(反射):在需要动态扩展产品时,工厂类可以使用反射加载产品类型:
public Product CreateProduct(string type) {
Type productType = Type.GetType(type);
return productType != null ? (Product)Activator.CreateInstance(productType) : null;
}特性 | 简单工厂模式 | 工厂方法模式 | 抽象工厂模式 |
|---|---|---|---|
复杂度 | 低 | 中 | 高 |
扩展性 | 差(需修改工厂类) | 良好(新增工厂子类即可) | 非常灵活(支持多个产品族) |
适用场景 | 产品种类少,扩展性要求低的场景 | 产品种类多但产品结构简单的场景 | 产品种类多且结构复杂的场景 |
将产品的创建参数化,可以更灵活地配置对象:
示例:
static std::unique_ptr<Product> createProduct(const std::string& type, int config) {
if (type == "A") {
return std::make_unique<ProductA>(config);
} else if (type == "B") {
return std::make_unique<ProductB>(config);
}
return nullptr;
}将简单工厂与单例模式结合,用于日志系统:
#include <iostream>
#include <string>
#include <memory>
class Logger {
public:
virtual void log(const std::string& message) = 0;
virtual ~Logger() {}
};
class FileLogger : public Logger {
public:
void log(const std::string& message) override {
std::cout << "File log: " << message << std::endl;
}
};
class ConsoleLogger : public Logger {
public:
void log(const std::string& message) override {
std::cout << "Console log: " << message << std::endl;
}
};
class LoggerFactory {
public:
static std::unique_ptr<Logger> getLogger(const std::string& type) {
if (type == "file") {
return std::make_unique<FileLogger>();
} else if (type == "console") {
return std::make_unique<ConsoleLogger>();
}
return nullptr;
}
};
int main() {
auto logger = LoggerFactory::getLogger("console");
if (logger) {
logger->log("Hello, world!");
}
return 0;
}简单工厂模式是一种结构简单但实用的设计模式,适合用于需求变化不频繁的小型项目或模块中,更多内容完善了简单工厂模式的局限性及改进方案,并扩展了实际应用案例,展示了模式的灵活性和变体的实现方法。但在扩展性要求高的场景中,推荐使用工厂方法模式或抽象工厂模式以增强灵活性。
欢迎关注、点赞、收藏!更多系列内容可以点击专栏目录订阅,感谢支持,再次祝大家祉猷并茂,顺遂无虞!

若将文章用作它处,请一定注明出处,商用请私信联系我!