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

查看:39
本文介绍了工厂模式和策略模式有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释工厂模式和策略模式之间的区别?

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)

推荐答案

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

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.

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

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.

这篇关于工厂模式和策略模式有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆