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


当前回答

延伸John Feminella的回答:

Apple, Banana, Cherry实现了FruitFactory,它有一个叫做Create的方法,它只负责创建Apple, Banana或Cherry。Factory方法就完成了。

现在,你想用你的水果创建一个特殊的沙拉,这就是你的抽象工厂。抽象工厂知道如何用苹果、香蕉和樱桃制作你的特殊沙拉。

public class Apple implements Fruit, FruitFactory {
    public Fruit Create() {
        // Apple creation logic goes here
    }
}

public class Banana implements Fruit, FruitFactory {
    public Fruit Create() {
        // Banana creation logic goes here
    }
}

public class Cherry implements Fruit, FruitFactory {
    public Fruit Create() {
        // Cherry creation logic goes here
    }
}

public class SpecialSalad implements Salad, SaladFactory {
    public static Salad Create(FruitFactory[] fruits) {
        // loop through the factory and create the fruits.
        // then you're ready to cut and slice your fruits 
        // to create your special salad.
    }
}

其他回答

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

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

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

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

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

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

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

对于John的回答,我有几点要补充如下:

抽象工厂是工厂中的工厂!

使用“Factory方法”(因为只有“Factory”是不明确的),您可以生成特定接口的实现(Lemon、Orange等)——比如,IFruit。这个工厂可以被称为CitricFruitFactory。

但是现在您想要创建CitricFruitFactory无法创建的另一种水果。如果您在CitricFruitFactory中创建一个草莓,那么它的代码可能就没有意义了(草莓不是柠檬酸水果!)。

所以你可以创建一个名为RedFruitFactory的新工厂,生产草莓,覆盆子等。

就像John Feminella说的: 使用抽象工厂模式,您可以生成特定工厂接口的实现——例如,IFruitFactory。他们每个人都知道如何创造不同种类的水果。”

IFruitFactory的实现是CitricFruitFactory和RedFruitFactory!

抽象工厂模式

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抽象工厂

工厂模式: 工厂生产iproduct实现

工厂模式: 一个工厂-工厂生产IFactories, IFactories反过来生产IProducts:)

[根据评论更新] 我之前写的至少在维基百科上是不正确的。抽象工厂就是一个简单的工厂接口。有了它,您可以在运行时切换工厂,以允许在不同的上下文中使用不同的工厂。例如针对不同操作系统的不同工厂、SQL提供者、中间件驱动程序等等。