tags:

views:

40

answers:

1

In our data layer, we need to create "style" objects that could inherit their values from other "style" objects.

Example scenario 1:

class Style
{
   string Name;
   string ParentName;
   // Other properties go here.
}

So, when there is a list of such styles, a style with a parent name should inherit it's style values from it's parent.

Scenario 2:

class ConatiningType
{
    Style BaseStyle;
    Style MouseHoverStyle;
}

In the above case, the MouseHoverStyle should inherit it's values from the BaseStyle.

I am sure there are some recommended design patterns for this scenario. If so, please point to those.

A: 

Perhaps Style itself should have a ParentStyle:

class Style
{
   private readonly Style parentStyle;

   private string name;

   public string Name
   {
       get { return name ?? (parentStyle == null ? null : parentStyle.Name); }
       set { name = value; }
   }

   public Style(Style parentStyle)
   {
       this.parentStyle = parentStyle;
   }
}

Having to use the null check on parentStyle is somewhat annoying, admittedly :( You could construct a "default" version like this, of course:

class Style
{
   private static readonly Style DefaultStyle = new Style(null) {
       Name = "",
       ... 
   };

   private readonly Style parentStyle;

   private string name;

   public string Name
   {
       get { return name ?? parentStyle.Name); }
       set { name = value; }
   }

   public Style(Style parentStyle)
   {
       this.parentStyle = parentStyle ?? DefaultStyle;
   }
}

Note that the DefaultStyle would still have a null parentStyle (as DefaultStyle would be null during its construction) but if you gave it actual default values ("", 0 etc) then it would never try to defer to its own non-existent parent.

Jon Skeet
Thanks, it's a perfectly valid answer.But, I am looking for a much more elaborate "pattern" that is a lot more scalable and performant, takes into account a lot more scenarios of "value inheritance" (is that the word I am looking for?), besides the 2 scenarios I outlined above.Thanks
@rqtechie: Where do you see the performance problems? It's hard to suggest approaches which will work for scenarios you haven't described...
Jon Skeet