title: Looking for a better design: A readonly in-memory cache mechanism
body: <p>I have a Category entity (class), which has zero or one parent Category and many child Categories -- it's a tree structure. The Category data is stored in a RDBMS, so <strong>for better performance, I want to load all categories and cache them in memory while launching the applicaiton.</strong></p>
  
  <p>Our system can have plugins, and we allow the plugin authors to access the Category Tree, but they should not modify the cached items and the tree(I think a non-readonly design might cause some subtle bugs in this senario), only the system knows when and how to refresh the tree.</p>
  
  <p>Here are some demo codes:</p>
  
  <pre><code>public interface ITreeNode&lt;T&gt;
      where T : ITreeNode&lt;T&gt;
  {
      // No setter
      T Parent { get; }
      IEnumerable&lt;T&gt; ChildNodes { get; }
  }
  
  // This class is generated by O/R Mapping tool (e.g. Entity Framework)
  public class Category : EntityObject
  {
      public string Name { get; set; }
  }
  
  // Because Category is not stateless, so I create a cleaner view class for Category.
  // And this class is the Node Type of the Category Tree
  public class CategoryView : ITreeNode&lt;CategoryView&gt;
  {
      public string Name { get; private set; }
  
      #region ITreeNode Memebers
  
      public CategoryView Parent { get; private set; }
  
      private List&lt;CategoryView&gt; _childNodes;
      public IEnumerable&lt;CategoryView&gt; ChildNodes {
          return _childNodes;
      }
  
      #endregion
  
      public static CategoryView CreateFrom(Category category) {
          // here I can set the CategoryView.Name property
      }
  }
  </code></pre>
  
  <p>So far so good. <strong>However, I want to make ITreeNode interface reuseable, and for some other types, the tree should not be readonly</strong>. We are not able to do this with the above readonly ITreeNode, so I want the ITreeNode to be like this:</p>
  
  <pre><code>public interface ITreeNode&lt;T&gt; {
      // has setter
      T Parent { get; set; }
      // use ICollection&lt;T&gt; instead of IEnumerable&lt;T&gt;
      ICollection&lt;T&gt; ChildNodes { get; }
  }
  </code></pre>
  
  <p><strong>But if we make the ITreeNode writable, then we cannot make the Category Tree readonly</strong>, it's not good.</p>
  
  <p>So I think if we can do like this:</p>
  
  <pre><code>public interface ITreeNode&lt;T&gt; {
      T Parent { get; }
      IEnumerable&lt;T&gt; ChildNodes { get; }
  }
  
  public interface IWritableTreeNode&lt;T&gt; : ITreeNode&lt;T&gt; {
      new T Parent { get; set; }
      new ICollection&lt;T&gt; ChildNodes { get; }
  }
  </code></pre>
  
  <p><strong>Is this good or bad? Are there some better designs? Thanks a lot! :)</strong></p>