[英]c# class design question
public class Service : IService
{
internal Configuration configuration;
public Response response;
public Service()
{
configuration = new Configuration();
configuration.Fetch();
}
public Response Execute(Request request)
{
switch case request.processtype
{
case ProcessType.Import:
Import import = new Import();
import.Configuration = configuration;
Response response = import.Execute(request)
case ProcessType.Export:
Export export = new Export();
export.Configuration = configuration;
Response response = export.Execute(request)
}
}
public class Import
{
public Configuration configuration;
public Response response;
public Response Execute(Request request)
{
response.AddMessage("doing something");
//some code
ImportSomething something = new ImportSomething();
something.Configuration = configuration;
something.Response = response;
response.AddMessage("doing more thing");
//more code
ImportSomethingElse somethingelse = new ImportSomethingElse();
somethingelse.Configuration = configuration;
somethingelse.Response = response;
return response;
}
public class ImportSomething
{
public Configuration configuration;
public Response response;
public Response Execute(Request request)
{
response.AddMessage("doing something");
//some code
response.AddMessage("doing more thing");
//more code
}
}
public class ImportSomethingElse
{
public Configuration configuration;
public Response response;
public Response Execute(Request request)
{
response.AddMessage("doing something");
//some code
response.AddMessage("doing more thing");
//more code
}
}
}
public class Export
{
public Configuration configuration;
public Response Execute(Request request)
{
}
}
public class Configuration
{
List<NameValue> Items;
public void Fetch()
{
//fetch from database
Items.Add("data");
}
}
public class Response
{
List<Message> Messages;
Public string Data;
public void AddMessage()
{
}
}
}
您会注意到,我正在将Configuration和Response对象传递给我正在调用的类。 我想知道这是否正确。 特别是我传递给每个类的响应对象是因为最终响应需要包括所有对象的消息。
您的实现没有任何真正的“错误”。 将这些对象传递给每个构造函数可能很麻烦。 这是工厂设计的目的之一,如果您想走那条路线,创建工厂,传入所需的配置和响应对象,然后从工厂创建所有其他对象,并依靠它来获取,这些对象传递到正确的位置。
使用IoC容器可以非常漂亮地完成此操作。 但是由于这是纯C#问题...
我将定义诸如Context之类的东西,并使用其实例(仅初始化一次)代替所有这些单独的设置:
public class CommandContext
{
public Configuration Configuration { get; protected set; }
public Request Request { get; protected set; }
public CommandContext(Configuration configuiration, ...) { ... }
}
...
public Response Execute(Request request)
{
var context = new CommandContext(configuration, request);
switch case request.processtype
{
case ProcessType.Import: return new Import().Execute(context);
case ProcessType.Export: return new Export().Execute(context);
}
}
同样,工厂模式可以帮助构建对象,从而进一步减少行数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.