6

我将要构建的软件将涉及很多不同状态之间的“应用程序”切换。可以完成的某些任务取决于应用程序所处的状态。我正在考虑使用枚举作为状态

public class Application
{
  public int Id {get;set;}
  public Status {get;set;}
}
public enum Status
{
  [Description("New")]New = 1, [Description("Closed")]Closed = 2
}

但是后来我想在数据库中使用查找表可能会很好,因为状态确实会经常更新/重新排序

table status (id int pk, desc string, sort_order int)
table application (id int pk, status_id int fk)

就我而言,我需要做类似的事情

if (application.Status == Status.New)
{ //do something }
else if (application.Status == Status.Closed)
{ //do other things }

我认为使用枚举更容易实现上述情况。但是,当涉及到更新状态排序顺序或描述时,它会非常困难。

我应该使用反射根据查找表中的值动态创建枚举吗?或者我应该使用状态模式?我看到枚举相关的问题是性能影响。而状态模式会产生大量的冗余代码。

你怎么看?提前致谢!

4

3 回答 3

7

你不应该在任何地方都用这个检查来洒你的代码

if (application.Status == Status.New)
{ //do something }
else if (application.Status == Status.Closed)
{ //do other things }

相反,使用状态模式。每当应用程序的模式发生变化时更改状态并将所有调用转发到状态的方法。您将拥有更清洁、更易于维护的代码。

至于改变状态,与状态模式无关。因此,您可以使用任何优雅的方法。

于 2009-03-04T07:08:38.943 回答
3

我会创建一个包含差异的 Status 类,然后调用它们。所以(在 ​​Python 中):

class StatusZero(object):
    def call_me(self, app):
       print 'Hello, from ' + app.name
       return db.prepare_specific_status_zero_request()


class StatusOne(object):
    def call_me(self, app):
        print 'Hi, from ' + app.name
        return db.prepare_specific_status_one_request()

states = { 'status_zero' : StatusZero(), 'status_one' : StatusOne() }

class Application(object):
    name = 'My App'
    status = states['status_zero']

    def change_state(self, state):
        status = state

    def call_me(self):
        state_key = self.status.call_me(self)
        self.change_state(states[state_key])

快速、易于保持功能分区,并且在状态之间具有合理的继承模式,您可以共享没有区别的功能。

于 2009-03-04T07:07:06.280 回答
0

我的理解是状态模式非常适合仅 UI 或仅内存执行,在我的情况下,当从应用程序表中检索数据时,仍然需要 if else 语句来确定要转换到的对象。

public AbstractApplication convert_db_application_to_object(obj db_application)
{
   AbstractApplication app;
   if (db_application.Status == (int)Status.New)
      app = application_factory.create(application_state_new);
   else if(db_application.Status == (int)Status.Closed)
      app = application_factory.create(application_state_closed);

   return app;
}

我不认为这是一个优雅的解决方案,因为我仍然需要一个枚举或查找表来将应用程序状态保存到数据库中

于 2009-03-04T09:51:11.940 回答