工厂模式和抽象工厂模式之间的基本区别是什么?
当前回答
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.
其他回答
工厂模式: 工厂生产iproduct实现
工厂模式: 一个工厂-工厂生产IFactories, IFactories反过来生产IProducts:)
[根据评论更新] 我之前写的至少在维基百科上是不正确的。抽象工厂就是一个简单的工厂接口。有了它,您可以在运行时切换工厂,以允许在不同的上下文中使用不同的工厂。例如针对不同操作系统的不同工厂、SQL提供者、中间件驱动程序等等。
工厂方法:您有一个工厂,它创建派生自特定基类的对象
抽象工厂:你有一个创建其他工厂的工厂,这些工厂反过来创建从基类派生的对象。这样做是因为您通常不只是想创建单个对象(与Factory方法一样)—相反,您想创建相关对象的集合。
我认为我们可以通过查看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!
抽象工厂是创建相关对象的接口,而工厂方法是一种方法。抽象工厂采用工厂方法实现。