具有基于时间的寿命的单身人士

时间:2016-04-14 15:12:31

标签: c# singleton

我正在尝试实现一个类似单身的类,它会有一个基于时间的生命周期。从程序开始每隔5秒创建的实例应该与普通单例中的实例相同,并且在不同的5秒跨度之间应该有不同的单例实例。我想出的是一个存储单例实例的列表,而不是典型的静态实例字段。但是,当我测试它时,我仍然得到相同的实例。这是代码:

route add x.y.z.w netmask 255.255.255.255 gateway a.b.c.d+1 metric 1

结果:class Program { static void Main(string[] args) { TimedSingleton t1 = TimedSingleton.Instance(); Thread.Sleep(5500); TimedSingleton t2 = TimedSingleton.Instance(); Console.WriteLine(t1 == t2); Console.ReadKey(); } } class TimedSingleton { private static ArrayList _instancesArrayList = new ArrayList(); private static List<int> AddedPositions = new List<int>(); private static DateTime _startTime = DateTime.Now; protected TimedSingleton() { } public static TimedSingleton Instance() { int index = (int) DateTime.Now.Subtract(_startTime).TotalSeconds%5; if (AddedPositions.Count == 0) { _instancesArrayList.Add(new TimedSingleton()); AddedPositions.Add(index); return (TimedSingleton)_instancesArrayList[index]; } if (AddedPositions.Contains(index)) { return (TimedSingleton) _instancesArrayList[index]; } AddedPositions.Add(index); _instancesArrayList.Add(new TimedSingleton()); return (TimedSingleton) _instancesArrayList[index]; } }

如何修复它以每5秒的时间间隔返回单独的实例?

1 个答案:

答案 0 :(得分:1)

而不是摆弄列表和arraylist中的索引,而是将实现改为使用泛型Dictionary<tkey, tvalue>,因此索引可以是简单的查找。请记住,这会不断添加项目,因此如果经常调用,则会耗尽内存。这里没有清理。

class TimedSingleton
{
    // have a dictonary to hold the seconds
    // and the instance so we can lookup
    private static Dictionary<int, TimedSingleton> AddedPositions = new Dictionary<int, TimedSingleton>();

    private static DateTime _startTime = DateTime.Now;

    protected TimedSingleton()
    {
    }

    public static TimedSingleton Instance()
    {
        // divide by 5
        int index = (int)DateTime.Now.Subtract(_startTime).TotalSeconds / 5;
        Debug.WriteLine(index);

        // 
        TimedSingleton result;
        // if you're going to multhreed this
        lock(AddedPositions)
        {
            // try to get the index seconds ...
            if (!AddedPositions.TryGetValue(index,out result))
            {
                // not happened
                Debug.WriteLine("Created new instance");
                result = new TimedSingleton();
                // store it for later
                AddedPositions.Add(index, result);
            }
            else
            {
                // result has now a previous instance
                Debug.WriteLine("from cache");
            }
        }
        return result;
    }
}