springboot设计模式-策略模式

在Spring Boot中,实现策略模式的最佳写法是使用Spring框架的依赖注入(DI)功能,以及使用@Bean注解将所有实现接口的类注册为Spring bean。

以下是实现策略模式的最佳写法的步骤:

  1. 创建一个接口,定义策略模式的方法:
public interface PaymentStrategy {
    void pay(double amount);
}
  1. 创建多个实现接口的类,实现策略模式的方法,并使用@Component注解将它们注册为Spring Bean:
@Component
public class CreditCardPaymentStrategy implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using credit card");
    }
}

@Component
public class PaypalPaymentStrategy implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " using PayPal");
    }
}

@Component
public class CashPaymentStrategy implements PaymentStrategy {
    @Override
    public void pay(double amount) {
        System.out.println("Paying " + amount + " in cash");
    }
}
  1. 创建一个策略工厂类,使用@Autowired注解将所有实现策略模式的类注入到工厂中:
@Component
public class PaymentStrategyFactory {
    private final Map paymentStrategies;

    @Autowired
    public PaymentStrategyFactory(List paymentStrategies) {
        this.paymentStrategies = paymentStrategies.stream()
                .collect(Collectors.toMap(PaymentStrategy::getClassSimpleName, Function.identity()));
    }

    public PaymentStrategy getPaymentStrategy(String paymentMethod) {
        return paymentStrategies.get(paymentMethod);
    }
}

在上述代码中,我们注入了所有实现PaymentStrategy接口的Spring Bean,并将它们存储在一个Map中。getPaymentStrategy方法接受一个字符串参数paymentMethod,表示要使用的支付方法,并返回相应的PaymentStrategy实现类。

  1. 创建一个服务类,在服务类中注入策略工厂类,并根据需求选择相应的策略:
@Service
public class PaymentService {
    private final PaymentStrategyFactory paymentStrategyFactory;

    @Autowired
    public PaymentService(PaymentStrategyFactory paymentStrategyFactory) {
        this.paymentStrategyFactory = paymentStrategyFactory;
    }

    public void processPayment(String paymentMethod, double amount) {
        PaymentStrategy paymentStrategy = paymentStrategyFactory.getPaymentStrategy(paymentMethod);
        paymentStrategy.pay(amount);
    }
}

在上述代码中,我们注入了PaymentStrategyFactory,并在processPayment方法中使用它来获取相应的PaymentStrategy实现类。

  1. 在应用中调用服务类的方法:
@SpringBootApplication
public class StrategyPatternDemoApplication implements CommandLineRunner {

    @Autowired
    private PaymentService paymentService;

    public static void main(String[] args) {
        SpringApplication.run(StrategyPatternDemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        double amount = 100.00;
        String paymentMethod = "CreditCardPaymentStrategy";
        paymentService.processPayment(paymentMethod, amount);
    }
}

在上述代码中,我们创建了一个Spring Boot应用,并在其中注入了PaymentService。然后在run方法中,我们调用了processPayment方法来执行具体的支付策略。

公众号: 代码极客(已接入chagpt3.5)

你可能感兴趣的:(java,springBoot,设计模式,策略模式,spring,boot,设计模式)