类型枚举
import lombok.Getter;
@Getter
public enum EventTypeEnum {
WE_CHAT(0),
ALI_PAY(1);
private int value;
EventTypeEnum(int value) {
this.value = value;
}
}
支付接口
/**
* @author yuhui_cai
*/
public interface IPayService {
/**
* 程序逻辑
* @return
*/
boolean dealEvent();
/**
* 获取事件类型
* @return
*/
int getType();
}
阿里支付实现类
import com.test.demo.textdemo.strategy.enumeration.EventTypeEnum;
import com.test.demo.textdemo.strategy.service.IPayService;
import org.springframework.stereotype.Service;
/**
* @author yuhui_cai
*/
@Service
public class AliPayServiceImpl implements IPayService {
@Override
public boolean dealEvent() {
System.out.println("aliPay");
return true;
}
@Override
public int getType() {
return EventTypeEnum.ALI_PAY.getValue();
}
}
微信支付实现类
import com.test.demo.textdemo.strategy.enumeration.EventTypeEnum;
import com.test.demo.textdemo.strategy.service.IPayService;
import org.springframework.stereotype.Service;
/**
* @author yuhui_cai
*/
@Service
public class WeChatServiceImpl implements IPayService {
@Override
public boolean dealEvent() {
System.out.println("weixin");
return true;
}
@Override
public int getType() {
return EventTypeEnum.WE_CHAT.getValue();
}
}
策略类
import com.test.demo.textdemo.strategy.service.IPayService;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class StrategyService {
Map<Integer, IPayService> eventServiceMap = new HashMap<>();
public StrategyService(List<IPayService> iStrategyServices) {
for (IPayService iStrategyService : iStrategyServices) {
eventServiceMap.put(iStrategyService.getType(), iStrategyService);
}
}
public boolean dealEvent(int eventType) {
IPayService iStrategyService = eventServiceMap.get(eventType);
return iStrategyService.dealEvent();
}
}
单元测试
@SpringBootTest(classes = TextDemoApplication.class)
@RunWith(SpringRunner.class)
public class TestDemo2 {
@Autowired
private StrategyService strategyService;
@Test
public void test(){
strategyService.dealEvent(0);
strategyService.dealEvent(1);
}
}
运行结果
2021-05-08 09:06:22.625 WARN 2408 --- [ main] c.b.m.core.metadata.TableInfoHelper : Can not find table primary key in Class: "com.test.demo.textdemo.entity.PmsSystemDatabase".
2021-05-08 09:06:23.345 INFO 2408 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-05-08 09:06:23.779 INFO 2408 --- [ main] yuhui.TestDemo2 : Started TestDemo2 in 3.612 seconds (JVM running for 4.746)
weixin
aliPay
2021-05-08 09:06:24.014 INFO 2408 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
2021-05-08 09:06:24.015 INFO 2408 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closing ...
2021-05-08 09:06:24.017 INFO 2408 --- [extShutdownHook] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} closed
Process finished with exit code 0