开发者

collections and application wide use?

Here's a specific problem that I run into when creating objects, such as collections, that need to be available through the whole scope of the appli开发者_Go百科cation.

I have the following class:

 class UserDataCollection
    {
        List<UserData> Collection = new List<UserData>();
        UserData current;

        public UserData Current
        {
            get { return current; }
            set 
            {
                current = value;
            }
        }

        public UserDataCollection( UserData userdata )
        {
            this.current = userdata;
        }

        public void Add ( UserData item )
        {
            Collection.Add(item);
        }


    }

Now for every UserData object I want to add, it's going to create a new List object each time I go UserDataCollection datacoll = new UserDataCollection(userdata);

So my objects will never be added to the same collection, which is not the point of this collection.

Is this then a good singleton case or just create the object at Application Init and use the same object throughout?

What's the best design practice for something like this?


You could just make the list static. Then there will only ever be one collection.


It depends

If it's a web application, you can create your collection on application start and store it into Application property of HttpContext. If not, you can use a singleton or an IoC container and configure it to always return the same instance of the object.

P.S : If multiple threads of the application will run simultaniously, by sure to use a lock before updating the collection.

Hope it will help.


Collections like this are for multiple objects obviously, so you would instantiate them where you are creating a ... collection of objects... If you want to use a ctor, then it should take as it's parameter a ... collection or enumerable set of those objects...

 // Inheriting from List<UserData> eliminates need for most of your code
 class UserDataCollection: List<UserData>
 {        
      public UserDataCollection(IEnumerable<UserData> users)
      {
          foreach (UserData usr in users)
              Add(usr);
      }  
 }


If there will only ever be one UserDataCollection per application then I don't see why not make it a singleton.


I like the idea of a Singleton here, if you only want one for your entire application. If you are using this in an ASP.NET application, you will have to watch out with Singletons because static variables are like saving data in Application state...which is probably what you want...but not easily noticeable to the outside world (maintainability issue).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜