1-定义一个抽奖接口LotteryService
public interface LotteryService {
/**
* 抽奖
*/
void lottery();
}
2-实现三种不同的抽奖策略
@Service("CharacterLotteryService")
public class CharacterLotteryServiceImpl implements LotteryService {
@Override
public void lottery() {
System.out.println("角色池抽奖");
}
}
@Service("IndefiniteLotteryService")
public class IndefiniteLotteryServiceImpl implements LotteryService {
@Override
public void lottery() {
System.out.println("常驻抽奖");
}
}
@Service("WeaponLotteryService")
public class WeaponLotteryServiceImpl implements LotteryService {
@Override
public void lottery() {
System.out.println("武器池抽奖");
}
}
@Service("xxx")里的内容是注入到Spring容器中bean的名字,等会使用策略工厂获取的时候需要用到;
3-定义一个枚举类,这样可以通过编码获取注入到Spring容器中的bean名称。
public enum LotteryEnum {
CHARACTER_ONE("00","IndefiniteLotteryService"),
CHARACTER_TWO("01","CharacterLotteryService"),
INDEFINITE("02","CharacterLotteryService"),
WEAPON("03","WeaponLotteryService");
/**
* 00-常驻 01-角色活动1 02-角色活动2 03-武器活动
*/
private String code;
/**
* 策略
*/
private String strategy;
LotteryEnum(String code, String strategy) {
this.strategy = strategy;
this.code = code;
}
public static String getStrategy(String code) {
for (LotteryEnum value : LotteryEnum.values()) {
if (value.getCode().equals(code)){
return value.getStrategy();
}
}
throw new ServiceException("没有该类型的策略");
}
public String getStrategy(){
return strategy;
}
public void setStrategy(String strategy) {
this.strategy = strategy;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
@Override
public String toString() {
return "LotteryEnum{" +
"strategy='" + strategy + '\'' +
", code='" + code + '\'' +
'}';
}
}
4-实现策略工厂类
@Service
public class LotteryStrategy {
@Resource
Map<String, LotteryService> map = new ConcurrentHashMap<>();
public LotteryService getLotteryService(String code){
String strategy = LotteryEnum.getStrategy(code);
return map.get(strategy);
}
}
使用@Resource注解可以获取到Spring容器中的三个具体策略的bean.用ConcurrentHashMap还可以防止线程不安全问题。
5-测试
@SpringBootTest
class LotteryStrategyTest {
@Resource
private LotteryStrategy lotteryStrategy;
@Test
void strategy(){
LotteryService lotteryService1 = lotteryStrategy.getLotteryService("01");
LotteryService lotteryService2 = lotteryStrategy.getLotteryService("02");
LotteryService lotteryService3 = lotteryStrategy.getLotteryService("03");
LotteryService lotteryService4 = lotteryStrategy.getLotteryService("00");
lotteryService1.lottery();
lotteryService2.lottery();
lotteryService3.lottery();
lotteryService4.lottery();
}
}
结果