枚举VS查找表VS枚举反射VS State模式
问题描述:
我将建设将涉及到“应用程序”的不同状态之间切换了大量的软件。某些任务可以完成取决于应用程序所处的状态。我想使用枚举的状态枚举VS查找表VS枚举反射VS State模式
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)
在我case我需要做的事情,如
if (application.Status == Status.New)
{ //do something }
else if (application.Status == Status.Closed)
{ //do other things }
我认为上面的情况是更容易做与枚举。但是,当涉及到更新状态排序顺序或描述时,这将非常困难。
我应该用反射基于从查找表值来动态创建枚举?或者我应该使用状态模式?我看到与枚举重新感谢问题是性能影响。状态模式会产生大量的冗余代码。
您认为如何?提前致谢!
答
我想创建一个包含差异的状态类,并调用这些。所以(在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])
快速,容易保持的功能划分,并且与状态之间的合理的遗传模式,你可以分享这没有什么不同的功能。
答
你不应该用这种检查洒你的代码到处
if (application.Status == Status.New)
{ //do something }
else if (application.Status == Status.Closed)
{ //do other things }
相反,使用状态模式。每当应用程序的模式发生变化时更改状态,并将所有调用转发给状态的方法。您将拥有更简洁,更易于维护的代码。
对于改变现状,已经什么都没有做的状态模式。所以你可以使用任何一种方法都很优雅。
答
我的理解是,国家模式是UI只或只在内存中执行,检索数据从申请表回来时,凡在我的情况,但仍然需要是如果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;
}
我不认为这是一个很好的解决方案 ,因为我还需要无论是枚举或查找表的应用程序状态保存到数据库
您是如何从数据库处理检索和转换为对象如果我在答案3中提到,否则没有其他陈述? – Jeff 2009-03-04 09:58:15