zoukankan      html  css  js  c++  java
  • [C#Util]ObjectPool Prototype

    下午不知道哪根筋不对劲了,突然去看看了最简单的DesignPattern之一的Singleton模式.看到了以前没有注意的一句话:只有一个实例只是最基本应用.在对象池中则要求多个实例.于是关于了一下对象池的实现.看了半天,好像多数的实现都是:http://blog.csdn.net/teddyma/archive/2006/01/11/4605987.aspx 这个版本的.看了会感觉这种简单的东西应该代码尽量简单才好.于是写了以下的版本.有什么问题,请大家指正.

    using System;
    using System.Collections;
    using System.Diagnostics;

    namespace DesignParttenProtype.Singleton.ObjectPool
    {
    publicclass ObjectPoolHelper<T>
    {
    privatestaticvolatile ObjectPoolHelper<T> _instance;
    privatestaticobject lockHelper =newobject();
    Queue _queue
    =new Queue();

    private ObjectPoolHelper(int poolSize)
    {
    while (poolSize >0)
    {
    poolSize
    --;
    _queue.Enqueue(Activator.CreateInstance
    <T>());
    // Thread.Sleep(1000);
    Debug.WriteLine("Add An Object Into ObjectPool Done!");
    }
    }

    ///<summary>
    /// GetInstance
    ///</summary>
    ///<param name="poolSize"></param>
    ///<returns></returns>
    publicstatic ObjectPoolHelper<T> GetSingletonInstance(int poolSize)
    {
    if (_instance ==null)
    {
    lock (lockHelper)
    {
    if (_instance ==null)
    {
    _instance
    =new ObjectPoolHelper<T>(poolSize);
    }
    }
    }

    return _instance;
    }

    ///<summary>
    /// Draw
    ///</summary>
    ///<returns></returns>
    public T Draw()
    {
    T obj;
    if (_queue.Count >0)
    {
    obj
    = (T)_queue.Dequeue();
    Debug.WriteLine(
    "Get An Object From Pool.");
    }
    else
    {
    obj
    = Activator.CreateInstance<T>();
    Debug.WriteLine(
    "Get New Object");

    }
    return obj;
    }

    ///<summary>
    /// Release
    ///</summary>
    ///<param name="type"></param>
    publicvoid Release(T type)
    {
    if (type !=null)
    {
    _queue.Enqueue(type);
    }
    }

    ///<summary>
    /// RemoveAll
    ///</summary>
    publicvoid RemoveAll()
    {
    _queue.Clear();
    }
    }
    }
  • 相关阅读:
    论线段树:二
    BST 二叉搜索树
    论线段树:一
    [luoguP3627][APIO2009]抢掠计划
    二分图匹配(匈牙利算法)
    SPFA 全面讲解
    markdown的常用高级操作。
    UVA11235 Frequent values
    P2279 [HNOI2003]消防局的设立
    P2216 [HAOI2007]理想的正方形
  • 原文地址:https://www.cnblogs.com/CopyPaster/p/1930216.html
Copyright © 2011-2022 走看看