支付通道使用策略模式替代if-else

背景:
在实际开发中,会接入很多不同支付通道,早期通道不太多且人手少项目时间紧的情况下,可以使用if-else。随着业务量不断扩大,接入的支付通道越来越多,假设还沿用之前方式的话,代码耦合度高、臃肿不好维护等缺点就是暴露。

策略模式简单运用

- 这里只是一个简单的例子,实际工作中会更复杂更贴近于业务逻辑。

  1. 抽象策略类
package com.example.demo.strategy;

public interface PaymentStrategy {

    void pay(String userId, String payNo);
}
  1. 具体策略实现类
    例如:微信支付、支付宝支付。
package com.example.demo.strategy;

import org.springframework.stereotype.Service;

@Service("wechat")
public class WechatPayment implements PaymentStrategy {
    @Override
    public void pay(String userId, String payNo) {
        System.out.printf("do WechatPayment...");
        return;
    }
}
package com.example.demo.strategy;

import org.springframework.stereotype.Service;

@Service("ali")
public class AliPayment implements PaymentStrategy {
    @Override
    public void pay(String userId, String payNo) {
        System.out.printf("do AliPayment...");
        return;
    }
}
  1. 策略模式工厂类
package com.example.demo.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class PaymentStrategyFactory {
    @Autowired
    Map<String, PaymentStrategy> factory = new ConcurrentHashMap<>();

    public PaymentStrategy getPaymentStrategy(String channel) {
        PaymentStrategy paymentStrategy = factory.get(channel);
        return paymentStrategy;
    }
}
  1. 单元测试类Test
package com.example.demo;

import com.example.demo.strategy.PaymentStrategy;
import com.example.demo.strategy.PaymentStrategyFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

	@Autowired
	PaymentStrategyFactory paymentStrategyFactory;

	@Test
	public void contextLoads() {
		PaymentStrategy py = paymentStrategyFactory.getPaymentStrategy("ali");
		py.pay("111","dddd");
	}

}

  1. 运行结果
    在这里插入图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值