背景:
在实际开发中,会接入很多不同支付通道,早期通道不太多且人手少项目时间紧的情况下,可以使用if-else。随着业务量不断扩大,接入的支付通道越来越多,假设还沿用之前方式的话,代码耦合度高、臃肿不好维护等缺点就是暴露。
策略模式简单运用
- 这里只是一个简单的例子,实际工作中会更复杂更贴近于业务逻辑。
- 抽象策略类
package com.example.demo.strategy;
public interface PaymentStrategy {
void pay(String userId, String payNo);
}
- 具体策略实现类
例如:微信支付、支付宝支付。
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;
}
}
- 策略模式工厂类
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;
}
}
- 单元测试类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");
}
}
- 运行结果