使用spring书写策略模式

写一个接口

public interface AccRuleFieldConvertProcessor {
    Object execute();
}

写三个实现类

一、

@Service(AccRuleField.WAY_CONST)
public class AccRuleFieldConvertConstImpl implements AccRuleFieldConvertProcessor {

}

二、

@Service(AccRuleField.WAY_COTRAST)
public class AccRuleFieldConvertConstImpl implements AccRuleFieldConvertProcessor {

}

三、

@Service(AccRuleField.WAY_FUNC)
public class AccRuleFieldConvertConstImpl implements AccRuleFieldConvertProcessor {

}

spring使用多个实现类

@Service
public class AccRuleFieldServiceImpl implements AccRuleFieldService {
    @Autowired(required = false)
    private Map<String, AccRuleFieldConvertProcessor> processorMap;

    @Override
    public Object convertFieldByWay(AccRuleFieldConvertDTO dto, AccRuleField accRuleField) {
        //accRuleField.getWay()的值为:  1.AccRuleField.WAY_CONST 2.AccRuleField.WAY_COTRAST  3.AccRuleField.WAY_FUNC
return Optional.ofNullable(processorMap)
.map(x -> x.get(accRuleField.getWay()))
.map(item->{item.execute(dto)})
.orElseThrow(() -> new RuntimeException("没有对应策略"));
        //return processorMap.get(accRuleField.getWay()).execute(dto);
    }
}