Manager/Container class vs static class methods

Posted by Ben on Programmers See other posts from Programmers or by Ben
Published on 2012-11-02T14:51:45Z Indexed on 2012/11/02 17:29 UTC
Read the original article Hit count: 393

Suppose I a have a Widget class that is part of a framework used independently by many applications. I create Widget instances in many situations and their lifetimes vary. In addition to Widget's instance specified methods, I would like to be able to perform the follow class wide operations:

  • Find a single Widget instance based on a unique id
  • Iterate over the list of all Widgets
  • Remove a widget from the set of all widgets

In order support these operations, I have been considering two approaches:

  1. Container class - Create some container or manager class, WidgetContainer, which holds a list of all Widget instances, support iteration and provides methods for Widget addition, removal and lookup. For example in C#:

    public class WidgetContainer : IEnumerable<Widget>  
    {  
      public void AddWidget(Widget);  
      public Widget GetWidget(WidgetId id);  
      public void RemoveWidget(WidgetId id);  
    }  
    
  2. Static class methods - Add static class methods to Widget. For example:

    public class Widget
    {
      public Widget(WidgetId id);
    
      public static Widget GetWidget(WidgetId id);
      public static void RemoveWidget(WidgetId id);
      public static IEnumerable<Widget> AllWidgets();  
    }
    

Using a container class has the added problem of how to access the container class. Make it a singleton?..yuck! Create some World object that provides access to all such container classes?

I have seen many frameworks that use the container class approach, so what is the general consensus?

© Programmers or respective owner

Related posts about c#

Related posts about design