我有以下代码:
interface IService
{
void Execute();
}
class ServiceA : IService
{
public void Execute() { ... }
}
class ServiceB : IService
{
public void Execute() { ... }
}
class ServiceComposite : IService
{
List<IService> _services = new List<IService>();
public ServiceComposite()
{
_services.Add(new ServiceA());
_services.Add(new ServiceB());
}
public void Execute()
{
foreach (IService service in _services)
{
service.Execute();
}
}
}
问题是ServiceB依赖于ServiceA的一些结果。我的想法是创建用于存储结果的容器类,然后将其注入ServiceA和ServiceB:
class ServiceResults
{
public string SomeProperty {get; set;}
}
public ServiceComposite()
{
ServiceResults result = new ServiceResults();
_services.Add(new ServiceA(result));
_services.Add(new ServiceB(result));
}
我想知道这是否是解决问题的最佳方法。也许它打破了我不知道的一些原则或规则,或者仅仅是#34;代码气味&#34;。有什么更好的方法呢?
答案 0 :(得分:1)
如果cpp cellSize 0.02
cpp min -0.25 -0.25 -0.25
cpp max 0.25 0.25 0.25
cellsize -1,79826e+36 min 0 1,21731e-37 0 max 1,21731e-37 0 1,21731e-37
需要ServiceB
的结果才能正常运行,那么为什么不ServiceA
取决于ServiceB
?
ServiceA
然后,如果您在集合中执行所有public interface IService
{
void Execute();
}
public class ServiceA : IService
{
public void Execute() { ... }
}
class ServiceB : IService
{
public ServiceB(IService service)
{
Service = service;
}
public void Execute() { ... }
public IService Servie { get; set; }
}
,则可以添加Service
以确保此服务仅执行一次:(完整示例)
在这个基本实现中,您可以添加:Async ServiceBase
,线程安全检查执行Execute
,Flyweight工厂生成特定InnerExecute
,有一个IService
,其中包含每个ResponseBase
....
Service
无论是谁使用这些public class ServiceResponse { }
public interface IService
{
ServiceResponse Execute();
}
public abstract class ServiceBase : IService
{
public ServiceResponse Execute()
{
if (_response == null)
{
_response = InnerExecute();
}
return _response;
}
public abstract ServiceResponse InnerExecute();
private ServiceResponse _response;
}
public class ServiceA : ServiceBase
{
public override ServiceResponse InnerExecute()
{
return new ServiceResponse();
}
}
public class ServiceB : ServiceBase
{
public ServiceB(IServiceFactory serviceFactory)
{
ServiceFactory= serviceFactory;
}
public override ServiceResponse InnerExecute()
{
return ServiceFactory.GetServices(ServicesTypes.ServiceA).Execute();
}
public IServiceFactory ServiceFactory { get; set; }
}
:
Service
可能你会想要通过一些映射键来访问工厂,可能你会想要public enum ServicesTypes
{
ServiceA,
ServiceB....
}
public interface IServiceFactory
{
IEnumerable<IService> GetServices();
IService GetServices(ServicesTypes servicesTypes);
}
public class SomeOtherThatExecuteServices
{
public SomeOtherThatExecuteServices(IServiceFactory serviceFactory)
{
ServiceFactory = serviceFactory;
}
public IEnumerable<ServiceResponse> ExecuteServices()
{
return ServiceFactory.GetServices()
.Select(service => service.Execute());
}
public IServiceFactory ServiceFactory { get; set; }
}
中的正确逻辑,但这一切都会让你以正确的方式(+使用一些合适的IoC容器)