直接给出代码:
首先是抽象类:
public abstract class Request
{
public string BuildRequest()
{
string body = BuildMessageBody();
string request = body + BuildMessageHeader();
return request;
}
protected string BuildMessageHeader()
{
return "Header"
}
protected abstract string BuildMessageBody();
}
继承后重写的2个类
public class ReverseRequest : Request
{
protected override string BuildMessageBody()
{
//do something
return "Reverse Request Body";
}
}
public class LoadRequest : Request
{
protected override string BuildMessageBody()
{
//do something
return "Load Request Body";
}
}
因需求不同返回不同的Rquest,使用:
private Request CreateRequstInstance()
{
if ("Reverse")
{
return new ReverseRequest();
}
else
{
return new LoadRequest();
}
}