Java工厂策略模式介绍

简介: 本文介绍Java中工厂模式与策略模式的结合应用,通过工厂创建策略对象,实现灵活、可扩展的支付、折扣等业务场景,提升系统解耦与维护性。

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();
    }
}

最佳实践

选择合适的工厂模式

场景 推荐模式
创建对象数量较少 简单工厂
需要扩展创建逻辑 工厂方法
创建相关对象族 抽象工厂
需要配置化管理 枚举工厂

策略模式使用原则

  1. 单一职责:每个策略类只负责一种算法
  2. 开闭原则:对扩展开放,对修改关闭
  3. 依赖倒置:依赖抽象而非具体实现
  4. 里氏替换:子类对象能够替换父类对象

性能考虑

  • 避免频繁创建策略对象
  • 使用对象池管理策略实例
  • 合理使用缓存机制
  • 考虑策略的生命周期管理

总结

工厂策略模式的结合使用为Java应用提供了强大的灵活性和可扩展性。通过工厂模式动态创建策略对象,通过策略模式灵活切换业务算法,这种组合模式特别适用于需要处理多种业务场景的系统。在实际应用中,应根据具体需求选择合适的实现方式,并注意性能优化和维护性考虑。



关于作者



🌟 我是suxiaoxiang,一位热爱技术的开发者

💡 专注于Java生态和前沿技术分享

🚀 持续输出高质量技术内容



如果这篇文章对你有帮助,请支持一下:




👍 点赞


收藏


👀 关注



您的支持是我持续创作的动力!感谢每一位读者的关注与认可!


目录
相关文章
|
24天前
|
设计模式 算法 搜索推荐
Java 设计模式之策略模式:灵活切换算法的艺术
策略模式通过封装不同算法并实现灵活切换,将算法与使用解耦。以支付为例,微信、支付宝等支付方式作为独立策略,购物车根据选择调用对应支付逻辑,提升代码可维护性与扩展性,避免冗长条件判断,符合开闭原则。
230 35
|
设计模式 算法 Java
Java中的策略模式
Java中的策略模式
138 1
|
设计模式 算法 Java
Java一分钟之-设计模式:策略模式与模板方法
【5月更文挑战第17天】本文介绍了策略模式和模板方法模式,两种行为设计模式用于处理算法变化和代码复用。策略模式封装不同算法,允许客户独立于具体策略进行选择,但需注意选择复杂度和过度设计。模板方法模式定义算法骨架,延迟部分步骤给子类实现,但过度抽象或滥用继承可能导致问题。代码示例展示了两种模式的应用。根据场景选择合适模式,以保持代码清晰和可维护。
360 1
|
设计模式 算法 Java
【十六】设计模式~~~行为型模式~~~策略模式(Java)
文章详细介绍了策略模式(Strategy Pattern),这是一种对象行为型模式,用于定义一系列算法,将每个算法封装起来,并使它们可以相互替换。策略模式让算法独立于使用它的客户而变化,提高了系统的灵活性和可扩展性。通过电影院售票系统中不同类型用户的打折策略案例,展示了策略模式的动机、定义、结构、优点、缺点以及适用场景,并提供了Java代码实现和测试结果。
【十六】设计模式~~~行为型模式~~~策略模式(Java)
|
设计模式 运维 算法
Java设计模式-策略模式(15)
Java设计模式-策略模式(15)
295 1
|
设计模式 缓存 算法
揭秘策略模式:如何用Java设计模式轻松切换算法?
【8月更文挑战第30天】设计模式是解决软件开发中特定问题的可重用方案。其中,策略模式是一种常用的行为型模式,允许在运行时选择算法行为。它通过定义一系列可互换的算法来封装具体的实现,使算法的变化与客户端分离。例如,在电商系统中,可以通过定义 `DiscountStrategy` 接口和多种折扣策略类(如 `FidelityDiscount`、`BulkDiscount` 和 `NoDiscount`),在运行时动态切换不同的折扣逻辑。这样,`ShoppingCart` 类无需关心具体折扣计算细节,只需设置不同的策略即可实现灵活的价格计算,符合开闭原则并提高代码的可维护性和扩展性。
184 2
|
移动开发 监控 供应链
JAVA智慧工厂制造生产管理MES系统,全套源码,多端展示(app、小程序、H5、台后管理端)
一开始接触MES系统,很多人会和博主一样,对MES细节的应用不了解,这样很正常,因为MES系统相对于其他系统来讲应用比较多!
508 1
JAVA智慧工厂制造生产管理MES系统,全套源码,多端展示(app、小程序、H5、台后管理端)
|
Java 关系型数据库 MySQL
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
UWB (ULTRA WIDE BAND, UWB) 技术是一种无线载波通讯技术,它不采用正弦载波,而是利用纳秒级的非正弦波窄脉冲传输数据,因此其所占的频谱范围很宽。一套UWB精确定位系统,最高定位精度可达10cm,具有高精度,高动态,高容量,低功耗的应用。
199 0
一套java+ spring boot与vue+ mysql技术开发的UWB高精度工厂人员定位全套系统源码有应用案例
|
设计模式 算法 Java
java策略模式简单分析
java策略模式简单分析
147 0
|
设计模式 算法 Java
Java 设计模式:探索策略模式的概念和实战应用
【4月更文挑战第27天】策略模式是一种行为设计模式,它允许在运行时选择算法的行为。在 Java 中,策略模式通过定义一系列的算法,并将每一个算法封装起来,并使它们可以互换,这样算法的变化不会影响到使用算法的客户。
190 1