工厂模式和抽象工厂模式之间的基本区别是什么?


当前回答

抽象工厂模式

Provide an interface for creating families of related or dependent objects without specifying their concrete classes. The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation. Actually, the delegated object frequently uses factory methods to perform the instantiation!

工厂模式

工厂模式就是这样的例子 创建型模式 创建模式抽象了 对象实例化过程。他们 隐藏对象是如何创建和帮助的 使整个系统相互独立 它的对象是如何创建的 组成。 类创建模式的重点 使用继承来决定 对象进行实例化 工厂方法 对象创建模式所关注的 实例化的委托 到另一个对象 抽象工厂

参考: 工厂vs抽象工厂

其他回答

抽象工厂模式

Provide an interface for creating families of related or dependent objects without specifying their concrete classes. The Abstract Factory pattern is very similar to the Factory Method pattern. One difference between the two is that with the Abstract Factory pattern, a class delegates the responsibility of object instantiation to another object via composition whereas the Factory Method pattern uses inheritance and relies on a subclass to handle the desired object instantiation. Actually, the delegated object frequently uses factory methods to perform the instantiation!

工厂模式

工厂模式就是这样的例子 创建型模式 创建模式抽象了 对象实例化过程。他们 隐藏对象是如何创建和帮助的 使整个系统相互独立 它的对象是如何创建的 组成。 类创建模式的重点 使用继承来决定 对象进行实例化 工厂方法 对象创建模式所关注的 实例化的委托 到另一个对象 抽象工厂

参考: 工厂vs抽象工厂

点击这里查看:http://www.allapplabs.com/java_design_patterns/abstract_factory_pattern.htm 似乎Factory方法使用一个特定的类(不是抽象类)作为基类,而抽象工厂则使用一个抽象类。此外,如果使用接口而不是抽象类,结果将是抽象工厂模式的不同实现。

:D

这些工厂的主要区别是什么时候你想用工厂做什么,什么时候你想使用它。

有时候,当你在做IOC(控制反转,例如构造函数注入)时,你知道你可以创建固体对象。如上面的水果示例所述,如果准备创建水果对象,可以使用简单的工厂模式。

但是很多时候,你不想创建实体对象,它们会在程序流的后面出现。但是配置告诉你你想在开始时使用什么样的工厂,而不是创建对象,你可以将从公共工厂类派生的工厂传递给IOC中的构造函数。

所以,我认为这也是关于对象的生命周期和创建。

使用Factory模式,您可以生成特定接口(例如,IFruit)的实现实例(Apple、Banana、Cherry等)。

使用抽象工厂模式,您可以为任何人提供他们自己的工厂提供一种方法。这使得您的仓库可以是IFruitFactory或IJuiceFactory,而不需要您的仓库了解任何关于水果或果汁的信息。

工厂方法和抽象工厂都使客户端与具体类型解耦。两者都创建对象,但是工厂方法使用继承,而抽象工厂方法使用组合。

工厂方法在子类中继承,用于创建具体的对象(产品),而抽象工厂提供了用于创建相关产品族的接口,这些接口的子类定义了如何创建相关产品。

然后这些子类在实例化后被传递到产品类中,在产品类中它被用作抽象类型。抽象工厂中的相关产品通常使用工厂方法来实现。