设计模式之Strategy模式(表驱动模式)

 
Strategy模式是应用比较广泛的模式之一,在我没有系统学习设计模式之前,我就一直使用该模式的思想进行设计。我想从一个例子来讲述该模式,假设有一个PDA的订餐系统,前端是Windows Mobile,后端为Web服务。服务员的PDA可以做以下三种操作,1.使用用户名密码登录到系统中。2.帮客户点菜下订单。3.对用餐结帐。前端不包含business logic,只是把请求通过WebService发送到后台。后台负责接收,处理请求,并回应处理结果。前后台通信可以通过webservice,remoting,WCF甚至socket进行通信,但这不是这篇文章讨论的内容,文章主要关注后台的设计。最直观简单的设计就是一个函数处理一种请求,实现如下:
 public enum RequestType
{
Login,
Order,
Payment
}

protected abstract class RequestHandler
{
public abstract bool ProcessRequest(DataSet ds);
protected void Abstract_Method()
{
//..
}
}

public class LoginHandler : RequestHandler
{
public bool ProcessRequest(DataSet ds)
{
//longin to the system
return true;
}

}

public class OrderHandler : RequestHandler
{
public bool ProcessRequest(DataSet ds)
{
//make an order
return true;
}

}

public class PaymentHandler : RequestHandler
{
public bool ProcessRequest(DataSet ds)
{
//make a payment
return true;
}

}

public sealed class RequestManager
{
private Dictionary<RequestType, RequestHandler> handlers;

public RequestManager()
{
handlers = new Dictionary<RequestType, RequestHandler>();

//it can use factory pattern here.
handlers[RequestType.Login] = new LoginHandler();
handlers[RequestType.Order] = new OrderHandler();
handlers[RequestType.Payment] = new PaymentHandler();
}

public bool Process(RequestType type, DataSet ds)
{
if (handlers.ContainsKey(type))
{
return handlers[type].ProcessRequest(ds);
}
return false;
}
    在Strategy模式的定义里面,Strategy抽象类定义要实现的算法接口,我认为应用范围不仅仅在算法,只要有共同点操作就可以定义这样的接口,定义这个接口的目的是制定一个契约,子类必须实现这个接口,也就是必须厉行这个契约。在我们的案例里面RequestHandler就是Strategy父类,这里可以定义为interface或者abstract class,这视乎于RequestHandler是否有子类共同的逻辑,如果有共同逻辑就定义为abstract class,把共同逻辑封装到protected的成员里面,没有就定义成interface。LoginHandler,OrderHandler和PaymentHandler等为RequestHandler的子类,他们必须实现ProcessRequest方法。RequestManager为Handlers的管理类,他管理着请求类型和处理类的映射关系,client只要调用RequestManager的Process进行处理,不用关心具体的处理类。Strategy很适合于编写framework,framework把总统的处理流程规定好,具体的交易流程根据interface来实现具体的处理类。例如我们这个系统扩展一下,规定每笔交易都需要操作数据库,写文件日志,进行侦听三步操作,那么可以定义三个处理的接口,每个处理类都需要实现相应的接口来满足总体流程。
posted on 2012-03-22 18:02  魂淡  阅读(1568)  评论(0编辑  收藏  举报