策略设计模式和状态设计模式有什么区别? [英] What is the difference between Strategy design pattern and State design pattern?

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

问题描述

策略设计模式和状态设计模式有什么区别?我在网上浏览了很多文章,但无法清楚地区分.

What are the differences between the Strategy design pattern and the State design pattern? I was going through quite a few articles on the web but could not make out the difference clearly.

有人可以解释一下外行术语的区别吗?

Can someone please explain the difference in layman's terms?

推荐答案

老实说,这两种模式在实践中非常相似,它们之间的定义差异往往会因您问的对象而异.一些流行的选择是:

Honestly, the two patterns are pretty similar in practice, and the defining difference between them tends to vary depending on who you ask. Some popular choices are:

  • 状态存储对包含它们的上下文对象的引用.策略没有.
  • 状态可以替换自己(即:将上下文对象的状态更改为其他状态),而策略则不能.
  • 策略作为参数传递给上下文对象,而状态由上下文对象本身创建.
  • 策略仅处理单个特定任务,而状态则为上下文对象所做的一切(或大部分)提供底层实现.

经典"实现将匹配列表中的每个项目的状态或策略,但您确实遇到了两者混合的混合体.一个特定的更倾向于 State-y 还是 Strategy-y 归根结底是一个主观问题.

A "classic" implementation would match either State or Strategy for every item on the list, but you do run across hybrids that have mixes of both. Whether a particular one is more State-y or Strategy-y is ultimately a subjective question.

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

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