好吧,我现在需要重构一个类,并在最好的情况下使用设计模式。我想这样做,以演示如何重构传统代码以服务于SOLID原则。直到现在,我所能做的只是提取方法。我有一个代码片段就在这里,这基本上填满了数据的一个对象从另一个对象:重构时使用设计模式
try {
final Object response = service.getOutput(InputData);
if (response instanceof OutputData) {
final OutputData output = (OutputData) response;
data.Quantity(output.getQuote().getQuantity());
data.setDate(output.getQuote().getDate());
data.setMaterial(productData.getCode());
if (isValidCustomer(output.getQuote())) {
data.setName(output.getQuote().getName());
} else {
data.setName("");
}
if (output.getQuote().getLimit() != null) {
data.setLimit(output.getQuote().getLimit().trim());
}
}
catch (final Exception e){
//...
}
if (productPrice != null) {
data.setProductPrice(productPrice);
data.setTotalPrice(calculateTotalPrice(data, productPrice, quantity));
}
什么是你能在这种情况下使用设计模式?问题是,该项目是基于Spring,所以它并不真正处理构造函数。正如你所看到的,已经有一些提取的方法,比如calculateTotalPrice等等。
嗯,它更多的是展示,如何使用它,以及它在理论上会带来哪些好处。我用Factory或Builder看到的问题是,他们经常使用构造函数来创建一个Object。 – user5417542