0. 描述
-
新增过滤器时,新增类继承基础过滤器抽象类,并实现父类抽象方法即可;删除过滤器时,删除相关过滤器类即可。实现热插拔过滤器链。
-
基于spring相关项目。
-
类图:
1. 过滤器链-ShopFilterChain
@Component
public class ShopFilterChain {
/**
* 过滤链
*/
private List<BashShopFilter> filterList = new ArrayList<>();
void addFilter(BashShopFilter filter) {
filterList.add(filter);
}
public List<BashShopFilter> getFilterList() {
return filterList;
}
}
2. 基础过滤器抽象类-BashShopFilter
public abstract class BashShopFilter {
@Autowired
private ShopFilterChain shopFilterChain;
/**
* 子类过滤器bean初始化时,回调该方法将当前过滤器加入过滤链
*/
@PostConstruct
private void init() {
shopFilterChain.addFilter(this);
}
/**
* 获取过滤器名
*
* @return
*/
public abstract String getFilterName();
public boolean doFilter(Shop shop) {
return this.filter(shop);
}
/**
* 判断店铺是否符合条件
* 子类过滤器需要实现具体判断逻辑
*
* @param shop
* @return
*/
protected abstract boolean filter(Shop shop);
}
3. 具体过滤器类-ShopCityFilter、ShopNameFilter、ShopTypeFilter
@Component
public class ShopCityFilter extends BashShopFilter {
private final static Long SHEN_ZHEN_CITY_ID = 440300000000L;
@Override
public String getFilterName() {
return "店铺城市过滤器";
}
@Override
protected boolean filter(Shop shop) {
if (shop.getCityId().equals(SHEN_ZHEN_CITY_ID)) {
return true;
}
System.out.println("店铺所在城市不是深圳市");
return false;
}
}
@Component
public class ShopNameFilter extends BashShopFilter {
private final static String PAN_PAN_SHOP_NAME = "胖胖食品";
@Override
public String getFilterName() {
return "店铺名称过滤器";
}
@Override
protected boolean filter(Shop shop) {
if (shop.getShopName().equals(PAN_PAN_SHOP_NAME)) {
return true;
}
System.out.println("店铺名称不是胖胖食品");
return false;
}
}
@Component
public class ShopTypeFilter extends BashShopFilter {
private final static Integer BRANDS_SHOP_TYPE = 2;
@Override
public String getFilterName() {
return "店铺类型过滤器";
}
@Override
protected boolean filter(Shop shop) {
if (shop.getShopType().equals(BRANDS_SHOP_TYPE)) {
return true;
}
System.out.println("店铺类型不是供应商");
return false;
}
}
4. 配置类-ShopFilterConfiguration
@Configuration
@Import({ShopCityFilter.class, ShopNameFilter.class, ShopTypeFilter.class, ShopFilterChain.class})
public class ShopFilterConfiguration {
}
5. 测试类-TestApplication
public class TestApplication {
public static void main(String[] args) {
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ShopFilterConfiguration.class);
Shop shop = new Shop("美美食品", 440300000000L, 2);
ShopFilterChain shopFilterChain = ctx.getBean(ShopFilterChain.class);
for (BashShopFilter shopFilter : shopFilterChain.getFilterList()) {
shopFilter.doFilter(shop);
}
}
}
-
运行后控制台返回:
店铺名称不是胖胖食品