开发过程中看到的代码,感觉很有趣,记录一下
创建工厂:
public class CompanyStrategyFactory {
private static Map<CompanyTypeEnum, CompanyStrategy> bases = new ConcurrentHashMap<>();
public static void register(CompanyTypeEnum typeCode, CompanyStrategy strategy) {
if (null == typeCode || null == strategy) {
return;
}
bases.put(typeCode, strategy);
}
public static CompanyStrategy get(CompanyTypeEnum type) {
return bases.get(type);
}
}
相关枚举类:
public enum CompanyTypeEnum implements IEnum<Integer>, EnumValidate<Integer> {
SUPPLIER(1, "供应商"),
PURCHASE(2, "采购企业"),
SYS_MANAGE(5, "运营角色"),
;
private Integer code;
private String message;
CompanyTypeEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
public Integer code() {
return this.code;
}
public String message() {
return this.message;
}
@Override
public boolean exist(Integer value) {
if (value == null) {
return false;
}
for (CompanyTypeEnum e : CompanyTypeEnum.values()) {
if (e.code().intValue() == value.intValue()) {
return true;
}
}
return false;
}
@Override
public Integer getValue() {
return this.code;
}
}
企业策略:
InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
public interface CompanyStrategy<T extends BaseBo> extends InitializingBean {
//这里继承了InitializingBean,InitializingBean里有afterPropertiesSet方法
viod test();
}
由于CompanyStrategy接口继承了InitializingBean接口,采购企CompanyStrategyPurchaseImpl和供应商CompanyStrategySupplierImpl分别实现了CompanyStrategy,并重写afterPropertiesSet()方法,这里是将对应的枚举和自身对象存到了Map里
/**
* @Description 供应商处理策略
*/
@Component
public class CompanyStrategySupplierImpl implements CompanyStrategy<SupplierDto> {
@Override
public void afterPropertiesSet() throws Exception {
CompanyStrategyFactory.register(CompanyTypeEnum.SUPPLIER, this);
}
@Override
public viod test(){
System.out.println("调用供应商相应方法");
}
}
/**
* @Description 采购企业处理策略
*/
@Component
public class CompanyStrategyPurchaseImpl implements CompanyStrategy<PurchaseDto> {
@Override
public void afterPropertiesSet() throws Exception {
CompanyStrategyFactory.register(CompanyTypeEnum.PURCHASE, this);
}
@Override
public viod test(){
System.out.println("调用采购企业相应方法");
}
}
我们具体调用可以通过CompanyStrategyFactory.get(companyTypeEnum);根据取map里的对象来调用采购企业或供应商。
/**
* 测试调用结果
*/
@Override
public void testResult() {
// 供应商
CompanyStrategy companyStrategy = CompanyStrategyFactory.get(CompanyTypeEnum.SUPPLIER);
//控制台打印“调用供应商相应方法”
companyStrategy.test();
// 采购企业
companyStrategy = CompanyStrategyFactory.get(CompanyTypeEnum.PURCHASE);
//控制台打印“调用采购企业相应方法”
companyStrategy.test();
}
了解工厂模式时看到这个博客,讲解的通俗易懂,想了解的可以看下