简单工厂模式
创建型模式
访问次数: 46
简单工厂模式是最简单的工厂模式,它通过一个工厂类来创建对象,而不需要知道具体的创建细节。
视频教程
类图
classDiagram
class Product {
<<interface>>
+operation()
}
class ConcreteProductA {
+operation()
}
class ConcreteProductB {
+operation()
}
class SimpleFactory {
+createProduct(type: String) Product
}
Product <|-- ConcreteProductA
Product <|-- ConcreteProductB
SimpleFactory --> Product
源代码示例
// 产品接口
interface Product {
void operation();
}
// 具体产品A
class ConcreteProductA implements Product {
@Override
public void operation() {
System.out.println("ConcreteProductA operation");
}
}
// 具体产品B
class ConcreteProductB implements Product {
@Override
public void operation() {
System.out.println("ConcreteProductB operation");
}
}
// 简单工厂
class SimpleFactory {
public static Product createProduct(String type) {
if ("A".equals(type)) {
return new ConcreteProductA();
} else if ("B".equals(type)) {
return new ConcreteProductB();
}
return null;
}
}
# 产品接口(抽象基类)
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def operation(self):
pass
# 具体产品A
class ConcreteProductA(Product):
def operation(self):
print("ConcreteProductA operation")
# 具体产品B
class ConcreteProductB(Product):
def operation(self):
print("ConcreteProductB operation")
# 简单工厂
class SimpleFactory:
@staticmethod
def create_product(product_type):
if product_type == "A":
return ConcreteProductA()
elif product_type == "B":
return ConcreteProductB()
else:
return None
# 使用示例
if __name__ == "__main__":
product_a = SimpleFactory.create_product("A")
product_b = SimpleFactory.create_product("B")
if product_a:
product_a.operation()
if product_b:
product_b.operation()
应用场景
当需要创建多种类型的对象,但创建逻辑相对简单时,可以使用简单工厂模式。应用场景包括:
1)图形绘制系统中需要创建不同类型的图形(圆形、矩形、三角形)
2)数据库连接管理,根据数据库类型(MySQL、Oracle、SQL Server)创建相应的连接对象
3)日志记录系统,根据日志级别(INFO、WARN、ERROR)创建不同类型的日志记录器
4)支付系统中根据支付方式(支付宝、微信、银行卡)创建对应的支付处理器
5)文件处理系统中根据文件类型(PDF、Word、Excel)创建相应的文件解析器
精选场景详解 —— 支付系统:按支付方式创建处理器
问题背景
电商下单后,用户可能选择支付宝、微信或银行卡支付。业务代码若直接 new 各支付类,会到处出现 if/else,新增支付方式时改动面大。
模式如何解决
选用简单工厂模式:把「创建哪个支付处理器」集中到 PaymentFactory。客户端只传入支付类型字符串(或枚举),工厂返回统一的 PaymentProcessor 接口。
这样做的好处:
1)创建逻辑集中,业务侧只依赖抽象接口;
2)新增支付渠道时,主要改工厂与新产品类;
3)创建规则简单(按 type 分支),适合简单工厂,而不必上完整工厂方法。
注意:若支付产品族很多、且创建规则还依赖平台/版本等复杂条件,可再演进为工厂方法或抽象工厂。
场景模型(角色映射)
将模式中的抽象角色映射到该业务领域的具体类:
classDiagram
class PaymentProcessor {
<<interface>>
+pay(amount: decimal) bool
+refund(orderId: String) bool
}
class AlipayProcessor {
+pay(amount: decimal) bool
+refund(orderId: String) bool
}
class WeChatProcessor {
+pay(amount: decimal) bool
+refund(orderId: String) bool
}
class BankCardProcessor {
+pay(amount: decimal) bool
+refund(orderId: String) bool
}
class PaymentFactory {
+create(type: String) PaymentProcessor
}
class CheckoutService {
+checkout(order: Order, payType: String)
}
PaymentProcessor <|.. AlipayProcessor
PaymentProcessor <|.. WeChatProcessor
PaymentProcessor <|.. BankCardProcessor
PaymentFactory --> PaymentProcessor : creates
CheckoutService --> PaymentFactory
CheckoutService --> PaymentProcessor : uses