【发布时间】:2019-02-11 17:23:56
【问题描述】:
我有具有不同实现的ProductHandler 类,例如ABCProductHandler、DEFProductHandler 等。它们是使用here 所示的命令模式从ProductServiceImpl 类调用的。
ProductServiceImpl 类:
@Service
public class ProductServiceImpl implements ProductService {
private Map<ProductType,ProductHandler> productHandlersMap =
new EnumMap<>(ProductType.class);
private ABCProductHandler abcProductHandler;
private DEFProductHandler defProductHandler;
//....10 other product handlers goes here
@Autowired
public ProductServiceImpl(ABCProductHandler abcProductHandler,
DEFProductHandler defProductHandler, .....) {
this.abcProductHandler = abcProductHandler;
this.defProductHandler = defProductHandler;
//....10 other product handlers goes here
}
@PostConstruct()
public void init() {
productHandlersMap.put(ProductType.ABC, abcProductHandler);
productHandlersMap.put(ProductType.DEF, defProductHandler);
//....10 other product handlers goes here
}
@Override
public ProductDetails calculateProductPrice(ProductType productType) {
productHandlersMap.get(productType).calculate();
//..some otehr code goes here
return productDetails;
}
}
但是,我对上面的 ProductServiceImpl 类不满意,因为有很多带有样板代码的 productHandlersMap.put 调用。
现在,我的问题是有什么方法可以轻松加载productHandlersMap?
@Service
public class ProductServiceImpl implements ProductService {
private Map<ProductType,ProductHandler> productHandlersMap =
new EnumMap<>(ProductType.class);
@PostConstruct()
public void init() {
//How to laod productHandlersMap easily with
// different ProductHandler types here?
}
@Override
public ProductDetails calculateProductPrice(ProductType productType) {
productHandlersMap.get(productType).calculate();
//..some other code goes here
return productDetails;
}
}
【问题讨论】:
标签: java spring dependency-injection