mercredi 23 août 2017

How to handle composed classes in C#

What I am asking is partly related to design pattern.

Lets say I have an IDrawing interface. Two other basic classes named TextDrawing and ShapeDrawing implement this, and I have a View class that knows how to draw these!

But I have more complex drawing classes that also implement IDrawing interface but are composed of several IDrawing classes themselves!

How can I draw these in my View class? Obviously teaching the View class to draw each new IDrawing is not a good idea! But what other choices I have? Maybe the design is not correct? How can I tell the View's Draw method to know the primitive parts of the complex classes and draw them?

   public interface IDrawing
   {
   }

   public class TextDrawing : IDrawing
   {
   }

   public class ShapeDrawing : IDrawing
   {      
   }

   public class SignDrawing : IDrawing
   {
      public TextDrawing Text { get; set; }
      public ShapeDrawing Border { get; set; }
   }

   public class MoreComplexDrawing : IDrawing
   {
      public TextDrawing Text { get; set; }
      public ShapeDrawing Border1 { get; set; }
      public ShapeDrawing Border2 { get; set; }
   }

   public class View
   {
      public void Draw(IDrawing drawing)
      {
           // The View only knows how to draw TextDrawing and ShapeDrawing.
           // These as the primitive building blocks of all drawings.
           // How can it draw the more complex ones!
           if (drawing is TextDrawing)
           {
              // draw it
           }
           else if (drawing is ShapeDrawing)
           {
              // draw it
           }
           else
           {
              // extract the drawings primitive parts (TextDrawing and ShapeDrawing) and draw them!
           }
      }
   }

Aucun commentaire:

Enregistrer un commentaire