工厂模式和战略模式的区别是什么?[英] What is the difference between Factory and Strategy patterns?

本文是小编为大家收集整理的关于工厂模式和战略模式的区别是什么?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

任何人都可以解释工厂和策略模式之间的区别吗?

对我来说,两者看起来都相同,而不是额外的工厂类(以工厂模式创建产品对象)

推荐答案

工厂模式是一种创造模式.策略模式是一种操作模式.换句话说,使用工厂模式来创建特定类型的对象.策略模式用于以特定方式执行操作(或一组操作).在经典的例子中,工厂可能会创建不同类型的动物:狗,猫,老虎,而策略模式将执行特定的动作,例如移动;使用跑步,步行或倾斜策略.

实际上两者可以一起使用.例如,您可能有一个创建业务对象的工厂.它可能会根据持久性媒介使用不同的策略.如果您的数据在本地存储在XML中,它将使用一种策略.如果数据在另一个数据库中是遥远的,则将使用另一个数据.

其他推荐答案

策略模式使您可以多态镀术的行为.

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

加里提出了一个很好的观点.如果您使用编码为抽象的原理而不是"具体",那么许多模式开始看起来像主题上的变体.

其他推荐答案

只是为了添加TVANFOSSON所说的话,许多模式看起来与实现相同.也就是说,您创建了一个界面,在您的代码中可能没有一个界面,然后创建一堆该界面的实现.区别在于他们的目的以及如何使用.

本文地址:https://www.itbaoku.cn/post/627656.html

问题描述

Can any one explain the difference between factory and strategy patterns?

For me both are looking same other than an extra factory class (which create an object of product in factory patterns)

推荐答案

A factory pattern is a creational pattern. A strategy pattern is an operational pattern. Put another way, a factory pattern is used to create objects of a specific type. A strategy pattern is use to perform an operation (or set of operations) in a particular manner. In the classic example, a factory might create different types of Animals: Dog, Cat, Tiger, while a strategy pattern would perform particular actions, for example, Move; using Run, Walk, or Lope strategies.

In fact the two can be used together. For example, you may have a factory that creates your business objects. It may use different strategies based on the persistence medium. If your data is stored locally in XML it would use one strategy. If the data were remote in a different database, it would use another.

其他推荐答案

The strategy pattern allows you to polymorphically change behavior of a class.

The factory pattern allows you to encapsulate object creation.

Gary makes a great point. If you are using the principle of coding to abstractions rather than "concretions" then a lot of the patterns start looking like variations on a theme.

其他推荐答案

Just to add to what tvanfosson said, a lot of the patterns look the same as far as implementation. That is, a lot have you create an interface where perhaps there wasn't one before in your code, and then create a bunch of implementations of that interface. The difference is in their purpose and how they are used.