工厂模式和抽象工厂模式之间的基本区别是什么?
当前回答
Abstract Factory is template for creating different type of interfaces. Suppose you have project that requires you to parse different types of csv files containing quantity, price and item specific information like some contain data about fruits other about chocolates and then after parsing you need to update this information in their corresponding database so now you can have one abstract factory returning you parser and modifier factory and then this parser factory can return you Chocolate parser object,Fruit Parser Object etc. and similarly Modifier Factory can return Chocolate modifier object , Fruit Modifier object etc.
其他回答
我认为我们可以通过查看Java8示例代码来理解这两者之间的区别:
interface Something{}
interface OneWhoCanProvideSomething {
Something getSomething();
}
interface OneWhoCanProvideCreatorsOfSomething{
OneWhoCanProvideSomething getCreator();
}
public class AbstractFactoryExample {
public static void main(String[] args) {
//I need something
//Let's create one
Something something = new Something() {};
//Or ask someone (FACTORY pattern)
OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeA = () -> null;
OneWhoCanProvideSomething oneWhoCanProvideSomethingOfTypeB = () -> null;
//Or ask someone who knows soemone who can create something (ABSTRACT FACTORY pattern)
OneWhoCanProvideCreatorsOfSomething oneWhoCanProvideCreatorsOfSomething = () -> null;
//Same thing, but you don't need to write you own interfaces
Supplier<Something> supplierOfSomething = () -> null;
Supplier<Supplier<Something>> supplierOfSupplier = () -> null;
}
}
现在的问题是你应该使用哪种创造方式以及为什么: 第一种方式(没有模式,只是普通的构造函数):自己创建不是一个好主意,你必须做所有的工作,你的客户端代码绑定到特定的实现。
第二种方式(使用Factory模式):为您提供了可以传递任何类型的实现的好处,这些实现可以基于某些条件(可能是传递给创建方法的参数)提供不同类型的东西。
第三种方法(使用抽象工厂模式):这为您提供了更多的灵活性。您可以根据某些条件(可能是传递的参数)找到不同类型的创建者。
请注意,您总是可以通过将两个条件组合在一起来摆脱工厂模式(这稍微增加了代码的复杂性和耦合),我想这就是为什么我们很少看到抽象工厂模式的实际用例。
对于John的回答,我有几点要补充如下:
抽象工厂是工厂中的工厂!
使用“Factory方法”(因为只有“Factory”是不明确的),您可以生成特定接口的实现(Lemon、Orange等)——比如,IFruit。这个工厂可以被称为CitricFruitFactory。
但是现在您想要创建CitricFruitFactory无法创建的另一种水果。如果您在CitricFruitFactory中创建一个草莓,那么它的代码可能就没有意义了(草莓不是柠檬酸水果!)。
所以你可以创建一个名为RedFruitFactory的新工厂,生产草莓,覆盆子等。
就像John Feminella说的: 使用抽象工厂模式,您可以生成特定工厂接口的实现——例如,IFruitFactory。他们每个人都知道如何创造不同种类的水果。”
IFruitFactory的实现是CitricFruitFactory和RedFruitFactory!
使用Factory模式,您可以生成特定接口(例如,IFruit)的实现实例(Apple、Banana、Cherry等)。
使用抽象工厂模式,您可以为任何人提供他们自己的工厂提供一种方法。这使得您的仓库可以是IFruitFactory或IJuiceFactory,而不需要您的仓库了解任何关于水果或果汁的信息。
工厂方法和抽象工厂都使客户端与具体类型解耦。两者都创建对象,但是工厂方法使用继承,而抽象工厂方法使用组合。
工厂方法在子类中继承,用于创建具体的对象(产品),而抽象工厂提供了用于创建相关产品族的接口,这些接口的子类定义了如何创建相关产品。
然后这些子类在实例化后被传递到产品类中,在产品类中它被用作抽象类型。抽象工厂中的相关产品通常使用工厂方法来实现。
抽象工厂是创建相关对象的接口,而工厂方法是一种方法。抽象工厂采用工厂方法实现。