Java工厂策略模式介绍
工厂模式和策略模式是Java开发中两个重要的设计模式,它们各自解决了不同的设计问题。工厂模式负责对象的创建,而策略模式处理算法的切换。将这两种模式结合使用,可以构建出灵活、可扩展的系统架构。
工厂模式详解
工厂模式是一种创建型设计模式,它提供了一种创建对象的最佳方式,而无需指定具体的类。工厂模式将对象的创建过程封装起来,使代码更加灵活和可维护。
简单工厂模式
简单工厂模式通过一个工厂类来创建不同类型的对象:
public class PaymentFactory {
public static PaymentProcessor createPaymentProcessor(String type) {
switch (type.toLowerCase()) {
case "credit_card":
return new CreditCardProcessor();
case "paypal":
return new PayPalProcessor();
case "alipay":
return new AlipayProcessor();
default:
throw new IllegalArgumentException("Unknown payment type: " + type);
}
}
}
工厂方法模式
工厂方法模式定义了一个创建对象的接口,但由子类决定实例化哪个类:
public abstract class PaymentProcessorFactory {
public abstract PaymentProcessor createPaymentProcessor();
public void processPayment(double amount) {
PaymentProcessor processor = createPaymentProcessor();
processor.process(amount);
}
}
public class CreditCardProcessorFactory extends PaymentProcessorFactory {
@Override
public PaymentProcessor createPaymentProcessor() {
return new CreditCardProcessor();
}
}
public class PayPalProcessorFactory extends PaymentProcessorFactory {
@Override
public PaymentProcessor createPaymentProcessor() {
return new PayPalProcessor();
}
}
抽象工厂模式
抽象工厂模式提供一个创建一系列相关或相互依赖对象的接口:
public interface PaymentFactory {
PaymentProcessor createProcessor();
PaymentValidator createValidator();
}
public class CreditCardPaymentFactory implements PaymentFactory {
@Override
public PaymentProcessor createProcessor() {
return new CreditCardProcessor();
}
@Override
public PaymentValidator createValidator() {
return new CreditCardValidator();
}
}
public class PayPalPaymentFactory implements PaymentFactory {
@Override
public PaymentProcessor createProcessor() {
return new PayPalProcessor();
}
@Override
public PaymentValidator createValidator() {
return new PayPalValidator();
}
}
策略模式详解
策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互换。策略模式让算法的变化独立于使用算法的客户。
策略接口定义
public interface PaymentStrategy {
boolean processPayment(double amount);
String getPaymentMethod();
}
具体策略实现
public class CreditCardStrategy implements PaymentStrategy {
private String cardNumber;
private String cvv;
private String expiryDate;
public CreditCardStrategy(String cardNumber, String cvv, String expiryDate) {
this.cardNumber = cardNumber;
this.cvv = cvv;
this.expiryDate = expiryDate;
}
@Override
public boolean processPayment(double amount) {
System.out.println("Processing credit card payment of $" + amount);
// 信用卡支付逻辑
return true;
}
@Override
public String getPaymentMethod() {
return "Credit Card";
}
}
public class PayPalStrategy implements PaymentStrategy {
private String email;
private String password;
public PayPalStrategy(String email, String password) {
this.email = email;
this.password = password;
}
@Override
public boolean processPayment(double amount) {
System.out.println("Processing PayPal payment of $" + amount);
// PayPal支付逻辑
return true;
}
@Override
public String getPaymentMethod() {
return "PayPal";
}
}
public class AlipayStrategy implements PaymentStrategy {
private String userId;
private String securityCode;
public AlipayStrategy(String userId, String securityCode) {
this.userId = userId;
this.securityCode = securityCode;
}
@Override
public boolean processPayment(double amount) {
System.out.println("Processing Alipay payment of $" + amount);
// 支付宝支付逻辑
return true;
}
@Override
public String getPaymentMethod() {
return "Alipay";
}
}
工厂策略模式结合
将工厂模式和策略模式结合使用,可以动态创建和选择合适的策略:
public class PaymentStrategyFactory {
public static PaymentStrategy createStrategy(String type, Map<String, String> params) {
switch (type.toLowerCase()) {
case "credit_card":
return new CreditCardStrategy(
params.get("cardNumber"),
params.get("cvv"),
params.get("expiryDate")
);
case "paypal":
return new PayPalStrategy(
params.get("email"),
params.get("password")
);
case "alipay":
return new AlipayStrategy(
params.get("userId"),
params.get("securityCode")
);
default:
throw new IllegalArgumentException("Unknown payment type: " + type);
}
}
}
public class PaymentContext {
private PaymentStrategy strategy;
public PaymentContext(PaymentStrategy strategy) {
this.strategy = strategy;
}
public void setStrategy(PaymentStrategy strategy) {
this.strategy = strategy;
}
public boolean executePayment(double amount) {
return strategy.processPayment(amount);
}
public String getPaymentMethod() {
return strategy.getPaymentMethod();
}
}
枚举工厂模式
使用枚举实现工厂模式,提供更安全的实现:
public enum PaymentType {
CREDIT_CARD {
@Override
public PaymentStrategy createStrategy(Map<String, String> params) {
return new CreditCardStrategy(
params.get("cardNumber"),
params.get("cvv"),
params.get("expiryDate")
);
}
},
PAYPAL {
@Override
public PaymentStrategy createStrategy(Map<String, String> params) {
return new PayPalStrategy(
params.get("email"),
params.get("password")
);
}
},
ALIPAY {
@Override
public PaymentStrategy createStrategy(Map<String, String> params) {
return new AlipayStrategy(
params.get("userId"),
params.get("securityCode")
);
}
};
public abstract PaymentStrategy createStrategy(Map<String, String> params);
public static PaymentStrategy create(String type, Map<String, String> params) {
return valueOf(type.toUpperCase()).createStrategy(params);
}
}
策略模式扩展
策略选择器
public class PaymentStrategySelector {
private Map<String, PaymentStrategy> strategies;
public PaymentStrategySelector() {
strategies = new HashMap<>();
strategies.put("credit_card", new CreditCardStrategy("1234", "123", "12/25"));
strategies.put("paypal", new PayPalStrategy("user@example.com", "password"));
strategies.put("alipay", new AlipayStrategy("user123", "code123"));
}
public PaymentStrategy getStrategy(String type) {
PaymentStrategy strategy = strategies.get(type.toLowerCase());
if (strategy == null) {
throw new IllegalArgumentException("Unknown payment type: " + type);
}
return strategy;
}
public void addStrategy(String type, PaymentStrategy strategy) {
strategies.put(type.toLowerCase(), strategy);
}
}
策略执行器
public class PaymentExecutor {
private PaymentStrategySelector selector;
public PaymentExecutor() {
this.selector = new PaymentStrategySelector();
}
public boolean processPayment(String type, double amount) {
PaymentStrategy strategy = selector.getStrategy(type);
return strategy.processPayment(amount);
}
public boolean processPayment(PaymentStrategy strategy, double amount) {
return strategy.processPayment(amount);
}
}
实际应用场景
电商系统支付模块
public class ECommercePaymentService {
private PaymentStrategyFactory factory;
public ECommercePaymentService() {
this.factory = new PaymentStrategyFactory();
}
public PaymentResult processOrder(Order order, String paymentType, Map<String, String> paymentDetails) {
try {
PaymentStrategy strategy = PaymentType.create(paymentType, paymentDetails);
PaymentContext context = new PaymentContext(strategy);
boolean success = context.executePayment(order.getTotalAmount());
if (success) {
// 更新订单状态
order.setStatus(OrderStatus.PAID);
return new PaymentResult(true, "Payment successful", context.getPaymentMethod());
} else {
return new PaymentResult(false, "Payment failed", null);
}
} catch (Exception e) {
return new PaymentResult(false, "Payment error: " + e.getMessage(), null);
}
}
}
折扣策略系统
public interface DiscountStrategy {
double calculateDiscount(double amount, Customer customer);
}
public class RegularDiscountStrategy implements DiscountStrategy {
@Override
public double calculateDiscount(double amount, Customer customer) {
return amount * 0.05; // 5% discount
}
}
public class VIPDiscountStrategy implements DiscountStrategy {
@Override
public double calculateDiscount(double amount, Customer customer) {
return amount * 0.15; // 15% discount
}
}
public class DiscountStrategyFactory {
public static DiscountStrategy createStrategy(CustomerType type) {
switch (type) {
case REGULAR:
return new RegularDiscountStrategy();
case VIP:
return new VIPDiscountStrategy();
default:
return new RegularDiscountStrategy();
}
}
}
配置化策略选择
配置文件
payment:
strategies:
- type: credit_card
class: com.example.CreditCardStrategy
enabled: true
- type: paypal
class: com.example.PayPalStrategy
enabled: true
- type: alipay
class: com.example.AlipayStrategy
enabled: false
配置化工厂
@Component
public class ConfigurablePaymentFactory {
@Value("${payment.strategies}")
private List<PaymentStrategyConfig> strategyConfigs;
private Map<String, Class<? extends PaymentStrategy>> strategyMap;
@PostConstruct
public void init() {
strategyMap = new HashMap<>();
for (PaymentStrategyConfig config : strategyConfigs) {
if (config.isEnabled()) {
try {
Class<?> clazz = Class.forName(config.getClassName());
strategyMap.put(config.getType(), (Class<? extends PaymentStrategy>) clazz);
} catch (ClassNotFoundException e) {
System.err.println("Class not found: " + config.getClassName());
}
}
}
}
public PaymentStrategy createStrategy(String type) {
Class<? extends PaymentStrategy> strategyClass = strategyMap.get(type);
if (strategyClass == null) {
throw new IllegalArgumentException("Unknown payment type: " + type);
}
try {
return strategyClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("Failed to create strategy: " + type, e);
}
}
}
性能优化
策略缓存
public class CachedPaymentStrategyFactory {
private static final Map<String, PaymentStrategy> cache = new ConcurrentHashMap<>();
public static PaymentStrategy createStrategy(String type, Map<String, String> params) {
String key = generateKey(type, params);
return cache.computeIfAbsent(key, k -> {
switch (type.toLowerCase()) {
case "credit_card":
return new CreditCardStrategy(
params.get("cardNumber"),
params.get("cvv"),
params.get("expiryDate")
);
case "paypal":
return new PayPalStrategy(
params.get("email"),
params.get("password")
);
case "alipay":
return new AlipayStrategy(
params.get("userId"),
params.get("securityCode")
);
default:
throw new IllegalArgumentException("Unknown payment type: " + type);
}
});
}
private static String generateKey(String type, Map<String, String> params) {
return type + "_" + params.hashCode();
}
}
最佳实践
选择合适的工厂模式
| 场景 | 推荐模式 |
|---|---|
| 创建对象数量较少 | 简单工厂 |
| 需要扩展创建逻辑 | 工厂方法 |
| 创建相关对象族 | 抽象工厂 |
| 需要配置化管理 | 枚举工厂 |
策略模式使用原则
- 单一职责:每个策略类只负责一种算法
- 开闭原则:对扩展开放,对修改关闭
- 依赖倒置:依赖抽象而非具体实现
- 里氏替换:子类对象能够替换父类对象
性能考虑
- 避免频繁创建策略对象
- 使用对象池管理策略实例
- 合理使用缓存机制
- 考虑策略的生命周期管理
总结
工厂策略模式的结合使用为Java应用提供了强大的灵活性和可扩展性。通过工厂模式动态创建策略对象,通过策略模式灵活切换业务算法,这种组合模式特别适用于需要处理多种业务场景的系统。在实际应用中,应根据具体需求选择合适的实现方式,并注意性能优化和维护性考虑。
关于作者
🌟 我是suxiaoxiang,一位热爱技术的开发者
💡 专注于Java生态和前沿技术分享
🚀 持续输出高质量技术内容
如果这篇文章对你有帮助,请支持一下:
👍 点赞
⭐ 收藏
👀 关注
您的支持是我持续创作的动力!感谢每一位读者的关注与认可!