我是小懒猴,人狠话不多,直接上才艺。
常规的策略模式
步骤:
- 数据DTO类
- 策略接口
- 实现策略类
- 执行器(经典的Context类)
- 实现类
数据DTO类
@Data
public class Stock {
private String code;
private Double price;
private Double rise;
}
策略接口
public interface Strategy {
List<Stock> sort(List<Stock> source);
}
实现策略类
public class HighPriceRank implements Strategy {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getPrice).reversed())
.collect(Collectors.toList());
}
}
public class HighRiseRank implements Strategy {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getRise).reversed())
.collect(Collectors.toList());
}
}
public class LowPriceRank implements Strategy {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getPrice))
.collect(Collectors.toList());
}
}
执行器
public class Context {
private Strategy strategy;
public void setStrategy(Strategy strategy) {
this.strategy = strategy;
}
public List<Stock> getRank(List<Stock> source) {
return strategy.sort(source);
}
}
实现类
@Service
public class RankServiceImpl {
public List<Stock> getRank(String rankType) {
Context context = new Context();
switch (rankType) {
case "HighPrice":
context.setStrategy(new HighPriceRank());
break;
case "LowPrice":
context.setStrategy(new LowPriceRank());
break;
case "HighRise":
context.setStrategy(new HighRiseRank());
break;
default:
throw new IllegalArgumentException("rankType not found");
}
return context.getRank(new ArrayList<Stock>());
}
}
--------------------------------------------------------------------------------
改造后的enum实现策略模式
步骤:
实现类
public enum RankEnum {
HighPrice {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getPrice).reversed())
.collect(Collectors.toList());
}
},
LowPrice {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getPrice))
.collect(Collectors.toList());
}
},
HighRise {
@Override
public List<Stock> sort(List<Stock> source) {
return source.stream()
.sorted(Comparator.comparing(Stock::getRise).reversed())
.collect(Collectors.toList());
}
};
public abstract List<Stock> sort(List<Stock> source);
}
实例RankServiceImpl
@Service
public class RankServiceImpl {
public List<Stock> getRank(String rankType) {
RankEnum rank = RankEnum.valueOf(rankType);
return rank.sort(new ArrayList<>());
}
}