有人能解释一下工厂模式和战略模式之间的区别吗?

对于我来说,两者看起来是一样的,除了一个额外的工厂类(在工厂模式中创建一个product对象)


当前回答

策略模式允许您多态地更改类的行为。

工厂模式允许封装对象创建。

加里说得很好。如果您使用的编码原则是抽象的,而不是“具体化”的,那么很多模式看起来就像是主题的变体。

其他回答

只是补充一下tvanfosson所说的,就实现而言,很多模式看起来都是一样的。也就是说,很多时候你创建了一个接口,而在你的代码中可能没有,然后创建了该接口的一堆实现。区别在于它们的目的和使用方式。

工厂模式是关于决定创建哪个对象,而策略模式是关于使用创建的对象。例如,使用哪种策略可以由工厂模式决定

策略模式允许您多态地更改类的行为。

工厂模式允许封装对象创建。

加里说得很好。如果您使用的编码原则是抽象的,而不是“具体化”的,那么很多模式看起来就像是主题的变体。

您不能仅仅通过查看代码或分类来理解其中的区别。要正确掌握GoF模式,请寻找它们的意图:

策略:“定义一系列算法,封装每个算法,并使它们可互换。策略让算法独立于使用它的客户而变化。”

工厂方法:定义一个用于创建对象的接口,但是让子类来决定实例化哪个类。工厂方法允许类延迟实例化到子类。

下面是关于这两种模式的意图和区别的详细解释:工厂方法和策略设计模式的区别

First of all a difference between simple factory and abstract factory must be made. The first one is a simple factory where you only have one class which acts as a factory for object creation, while in the latter you connect to an factory interface (which defines the method names) and then call the different factories that implement this interface which are supposed to have different implementations of the same method based on some criteria. For example, we have a ButtonCreationFactory interface, which is implemented by two factories, the first WindowsButtonCreationFactory (creates buttons with Windows look and feel) and the second LinuxButtonCreationFactory (creates buttons with Linux look and feel). So both these factories do have the same creation method with different implementations (algorithms). You can reference this in runtime based on the method that you type of button that you want.

例如,如果你想要带有Linux外观和感觉的按钮:

ButtonCreationFactory myFactory = new LinuxButtonCreationFactory();
Button button1 = myFactory.createButton(...);

或者你想要Windows按钮

ButtonCreationFactory myFactory = new WindowsButtonCreationFactory();
Button button1 = myFactory.createButton(...);

Exactly in this case, it results in a kind of strategy pattern, since it differentiates algorithms for doing some creation. However, it differs from it semantically because it is used for OBJECT CREATION rather than operational algorithms. So, basically with abstract factory you have object creation using different strategies, which makes it very similar to the strategy pattern. However the AbstractFactory is creational, while the Strategy pattern is operational. Implementation wise, they result to be the same.