假设我有一家工厂,它基于一次性资源创建服务。我认为第一个解决方案是最干净的,但我无法弄清楚如何在我的情况下处理“实例”。第二个将是一个解决方案,但可以称为工厂吗?我不这么认为,因为它拥有适当的资源。此外,“DisposableIOResource”是那种很难创建的服务,你只想躲在工厂后面。有解决这种情况的好模式吗?在我的两个草稿片段下方。
// first solution
public class ServiceFactory
{
public Reader CreateReader(string configuration)
{
var instance = new DisposableIOResource(configuration);
return new Reader(instance);
}
}
// first solution - use case
var serviceFactory = new ServiceFactory();
var reader = serviceFactory.CreateReader(configuration)
reader.DoSomething(); // NOTE! How do I dispose 'instance'???
// second solution
public class ServiceFactory : IDisposable
{
private readonly DisposableIOResource _instance;
public ServiceFactory(string configuration)
{
_instance = new DisposableIOResource(configuration);
}
public Reader CreateReader()
{
return new Reader(_instance);
}
public void Dispose()
{
_instance.Dispose();
}
}
// second solution - use case
using(var serviceFactory = new ServiceFactory(configuration))
{
var reader = serviceFactory.CreateReader():
reader.DoSomething();
}
---编辑我最终得到了另一种解决方案,也许是一个更清洁的解决方案:
public interface IDisposableIOResourceFactory
{
DisposableIOResource Create();
}
public class DisposableIOResourceFactory : IDisposableIOResourceFactory
{
private readonly string _configuration;
public DisposableIOResourceFactory(string configuration)
{
_configuration = configuration;
}
public DisposableIOResource Create()
{
return new DisposableIOResource(this._configuration);
}
}
// third solution
public class ServiceFactory
{
public Reader CreateReader(IDisposableIOResourceFactory resourceFactory)
{
return new Reader(resourceFactory);
}
}
public class Reader
{
public Reader(IDisposableIOResourceFactory resourceFactory) {}
public void DoSomething()
{
using var resource = resourceFactory.Create();
// work on resource
}
}
// first solution - use case
var serviceFactory = new ServiceFactory();
var resourceFactory = new DisposableIOResourceFactory();
var reader = serviceFactory.CreateReader(resourceFactory);
reader.DoSomething();