我似乎在精神上陷入了享元模式的困境。
首先,假设我有一个一次性类型DisposableFiddle
和一个工厂FiddleFactory
:
public interface DisposableFiddle : IDisposable
{
// Implements IDisposable
}
public class FiddleFactory
{
public DisposableFiddle CreateFiddle(SomethingThatDifferentiatesFiddles s)
{
// returns a newly created fiddle.
}
}
然后,在我看来,客户很清楚FiddleFactory
工厂声称对创建的小提琴没有所有权,并且客户有责任在处理完小提琴后处理它。
但是,假设我想通过使用享元模式在客户端之间共享小提琴:
public class FiddleFactory
{
private Dictionary<SomethingThatDifferentiatesFiddles, DisposableFiddle> fiddles = new ...;
public DisposableFiddle CreateFiddle(SomethingThatDifferentiatesFiddles s)
{
// returns an existing fiddle if a corresponding s is found,
// or a newly created fiddle, after adding it to the dictionary,
// if no corresponding s is found.
}
}
然后我觉得在道德上有义务让工厂本身是一次性的,因为它创造了小提琴并在他们的一生中保持对它们的引用。但这会给假设他们拥有小提琴并因此应该处置它们的客户带来问题。
问题实际上是我调用工厂FiddleFactory
而不是,说,FiddlePool
和“创建”方法CreateFiddle
而不是GetFiddle
?像这样:
public class FiddlePool : IDisposable
{
private Dictionary<SomethingThatDifferentiatesFiddles, DisposableFiddle> fiddles = new ...;
public DisposableFiddle GetFiddle(SomethingThatDifferentiatesFiddles s)
{
// returns an existing fiddle if a corresponding s is found,
// or a newly created fiddle, after adding it to the dictionary,
// if no corresponding s is found.
}
// Implements IDisposable
}
然后,客户就更清楚它不会拥有返回的小提琴,并且处理小提琴是池的责任。
还是只能通过文档轻松解决?
有没有办法摆脱困境?甚至有两难境地吗?:-)