English 中文(简体)
状态模式对 ENUM 的状态模式
原标题:State pattern vs ENUM

有时,它需要支持国家对物体的支持。

  1. ENUM (SIMPLE)
  2. STATE pattern (OC principle)

显然,需要为此目的使用国家模式(我不确定)。

But reading other code I often face with enum only not state pattern at all. Does state pattern has power?

最佳回答

为什么我们使用国家模式? 消除有条件的逻辑重复,用多种形态取代有条件的代码。

什么时候我们有有条件的逻辑重复? 当我们有许多取决于国家的行动时,你必须在每一个行动中重复你的有条件的逻辑。当你有很多国家的时候,它就会变得非常令人烦恼。 代码重复意味着当你加入新的国家时,你应该更新每一个重复的代码。

因此,如果我没有重复有条件逻辑,我宁可采用基于enum的状态,而不要为各州建立新的等级等级体系,为各州创造许多等级。 有时我甚至更喜欢有条件逻辑重复:比如,当我有许多州,但只有极少数国家独立行动。 在这种情况下,我宁愿有两个切换区块,而不是创建十个新等级。

问题回答

一般来说, EENUM 方法涉及某种状态和转变的表格(数组)。而设计模式在对象上也实现了相同的效果。

如果您没有提及与ENUMs的表格方法,那么如果块块(如果块块)非常难以管理,那么解决方案就需要涉及一个大的如果/ele(如果块),而块块则相当难以管理。 关于下面的一节,我想很明显的是,这个特定的解决方案是低级的。

以下是我所列举的,作为每个项目的方案和国家委员会。

<强 > ENUM表

方案:

  • Easier to see all of the states and transitions since the table is defined in one place

国家理事会:

  • States and transitions are more hard-coded and more code changes are needed to extend

<强 > 设计模式

方案:

  • Easier to extend with new states by adding a new object. (Open/Close Principle)
  • Easier to assure that all signals are treated by the states, since the base class should define the signals as abstract functions.
  • Easier to extend a particular states behavior by deriving from the state. The state pattern should put a particular state s behavior in one object.

国家理事会:

  • More difficult to see all states and their relations by looking at code, since they are dispersed among several different classes.
  • Could end up creating an unmanageable number of objects. But compare this to the corresponding if/else blocks needed with the corresponding ENUM solution.




相关问题
Choosing the right subclass to instantiate programmatically

Ok, the context is some serialization / deserialization code that will parse a byte stream into an object representation that s easier to work with (and vice-versa). Here s a simplified example ...

Design pattern for managing queues and stacks?

Is there a design pattern for managing a queue or a stack? For example, we are looking to manage a list of tasks. These tasks will be added to a group queue, users will then be able to pull off the ...

Organizing classes using the repository design pattern

I have started upgrading one of our internal software applications, written in ASP.NET Web Forms, and moving to ASP.NET MVC. I am trying to leverage the Repository design pattern for my classes, ...

Misuse of Observer Pattern?

I have a Car object which contains a latitude field and a longitude field. I use the observer pattern so that any time either of these fields change in my application, my car object is notified. I ...

How are Models (in MVC) and DAOs supposed to interact?

How are models and DAOs supposed to interact? I m in the process of putting together a simple login module and I m unsure where to put the "business logic." If I put the logic with the data in the ...

热门标签