我对使用哪种模式/最适合我的要求感到困惑。我希望你能澄清一下。不确定是否使用建筑商或工厂。
情景就是这样。 创建一个请求对象并将其传递给我无法控制的第三方组件
请求可以是多种类型 - EmployeeRequest-WorkerRequest-etc. ...每个请求都有像“GetXXX”-GetYYY“等方法。
Noddy的例子 我做了如下:
class Program
{
static void Main()
{
Request employeeRequest = new EmployeeRequest { Id=1,FirstName = "Foo", LastName = "Bar" };
Service myservice=new Service();
var response = myservice.DoSomething(employeeRequest);
//do something with the response ...
}
}
public class Service
{
public Response DoSomething(Request request)
{
Factory factory = new Factory();
Request myRequest = factory.Create(request);
//Call my third party component
//Response myResponse = MyThirdPartyComponent.DoSomething(myRequest);
//return myResponse;
return new Response();
}
}
public class Factory
{
public Request Create(Request request)
{
if (request is EmployeeRequest)
{
EmployeeRequest employeeRequest = new EmployeeRequest();
employeeRequest.FirstName = request.FirstName;
employeeRequest.LastName = request.LastName;
return employeeRequest;
}
else
{
WorkerRequest workerRequest = new WorkerRequest();
workerRequest.FirstName = request.FirstName;
workerRequest.LastName = request.LastName;
return workerRequest;
}
}
}
public abstract class Request
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Response
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class EmployeeRequest : Request
{}
public class WorkerRequest : Request
{}
public class EmployeeResponse : Response
{}
public class WorkerResponse : Response
{}
如果你要实现它,你会怎么做:
由于
答案 0 :(得分:0)
我个人而不是让Factory
来构建我的请求,可能会将抽象方法Request GetRequest()
添加到Request
抽象类,并在每个EmployeeRequest
中实现其具体实现},WorkerRequest
,....
因为,至少看看提供的代码,你要做的是:
创建EmployerRequest
并将其分配给Request
将其传递给Factory
的方法以使is
并创建EmployerRequest
“克隆”以传递给服务器。真的不知道你是否真的需要它,但假设是,那么,为什么只是不要问对象本身创建另一种类型的本身?
希望这清楚我的意见。
问候。
答案 1 :(得分:0)
如果您只是尝试为继承Request
的类型填写Request
基类型的属性,请创建一个通用方法(您可能需要稍微更改一下模型):
void Main()
{
var request = new WorkRequest();
request.FirstName = "joe";
request.LastName ="smith";
var employeeRequest = RequestFactory.Create<EmployeeRequest>(request);
System.Diagnostics.Debug.Assert(employeeRequest.FirstName == request.FirstName);
}
public class RequestFactory
{
public static T Create<T>(Request request)
where T : Request, new()
{
return (T)Activator.CreateInstance(typeof(T), request);
}
}
public abstract class Request
{
protected Request() {}
protected Request(Request request)
{
this.FirstName = request.FirstName;
this.LastName = request.LastName;
}
public string FirstName {get;set;}
public string LastName {get;set;}
}
public class EmployeeRequest : Request
{
public EmployeeRequest(){}
public EmployeeRequest(Request request)
: base(request)
{
}
}
public class WorkRequest : Request
{
public WorkRequest(){}
public WorkRequest(Request request)
: base(request)
{
}
}