我似乎在精神上陷入了Flyweight模式的困境。
首先,假设我有一次性用品 DisposableFiddle
和一个工厂 FiddleFactory
:
public interface DisposableFiddle : IDisposable
{
// Implements IDisposable
}
public class FiddleFactory
{
public DisposableFiddle CreateFiddle(SomethingThatDifferentiatesFiddles s)
{
// returns a newly created fiddle.
}
}
然后,在我看来,对客户来说很清楚 FiddleFactory
工厂声称没有所创造的小提琴的所有权,并且客户有责任在完成它时处理小提琴。
但是,让我们说我想通过使用Flyweight模式在客户端之间共享小提琴:
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
}
然后对客户来说更清楚的是它不会拥有返回的小提琴,并且游泳池有责任处理小提琴。
或者这只能在文档方面轻松解决吗?
有没有办法摆脱困境?还有进退两难的局面吗? :-)