了解抽象工厂模式 [英] Understanding Abstract Factory pattern
问题描述
我已经阅读了关于 wiki 的抽象工厂模式。但是通过使用这种模式,我不了解真正的利润。你能否得到一个很难避免抽象工厂模式的例子。考虑以下Java代码:
I've read about abstract factory patter on wiki. But I don't understand really profit by using this pattern. Can you get an example in which is hard to avoid abstract factory pattern. Consider the following Java code:
public abstract class FinancialToolsFactory {
public abstract TaxProcessor createTaxProcessor();
public abstract ShipFeeProcessor createShipFeeProcessor();
}
public abstract class ShipFeeProcessor {
abstract void calculateShipFee(Order order);
}
public abstract class TaxProcessor {
abstract void calculateTaxes(Order order);
}
// Factories
public class CanadaFinancialToolsFactory extends FinancialToolsFactory {
public TaxProcessor createTaxProcessor() {
return new CanadaTaxProcessor();
}
public ShipFeeProcessor createShipFeeProcessor() {
return new CanadaShipFeeProcessor();
}
}
public class EuropeFinancialToolsFactory extends FinancialToolsFactory {
public TaxProcessor createTaxProcessor() {
return new EuropeTaxProcessor();
}
public ShipFeeProcessor createShipFeeProcessor() {
return new EuropeShipFeeProcessor();
}
}
// Products
public class EuropeShipFeeProcessor extends ShipFeeProcessor {
public void calculateShipFee(Order order) {
// insert here Europe specific ship fee calculation
}
}
public class CanadaShipFeeProcessor extends ShipFeeProcessor {
public void calculateShipFee(Order order) {
// insert here Canada specific ship fee calculation
}
}
public class EuropeTaxProcessor extends TaxProcessor {
public void calculateTaxes(Order order) {
// insert here Europe specific tax calculation
}
}
public class CanadaTaxProcessor extends TaxProcessor {
public void calculateTaxes(Order order) {
// insert here Canada specific tax calculation
}
}
如果我们需要在代码中创建对象在代码中1-2次以下,那么我们只能使用新的操作符。为什么我们需要抽象工厂?
If we need to just create objects in a code below 1-2 times in a code then we can use just new operator. And why we need in abstract factory?
推荐答案
你缺少一半的工作:)
void processOrder(FinancialToolsFactory ftf,Order o) {
tft.createTaxProcessor().calculateTaxes(o);
tft.createShipFeeProcessor().calculateShipFee(o);
}
此代码与您通过加拿大元或欧洲执行 FinancialToolsFactory
(您可以将实现者类外部化为外部资源,并使用Class.newInstance()实例化)。
this code works as well as you pass a canadian or european implementation of FinancialToolsFactory
(you can externalize the implementor class to external resource and instantiate with a Class.newInstance(), for example).
在这种情况下,模式使用的真正好处之一是不编写实现模式的代码,而是使用该代码!
In this case one of the real benefits of pattern usage is not writing the code that implements the pattern, but who use that code!
PS:我的答案是故意不完整的,并尝试回答这个具体问题;关于模式和他们的好处的讨论太大了!
PS: My answer is intentionally incomplete and try to answer just this specific question; a discussion about pattern and their benefits is too big!
这篇关于了解抽象工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!