Layer Supertype pattern with example in C#

First of all look at the definition by @martinfowler "A type that acts as the supertype for all types in its layer" all you need is a Supertype Class for all the Objects. I usually use it in Repository layer as a generic Repository. I recommend to use it if you have more than one kind of object in your layer. Let's consider an example in real world , Create a class and name it Profile

  1.    public class Profile
  2.     {
  3.         public string Name { get; set; }
  4.         public int Age { get; set; }
  5.     }

 Then create a generic interface called IRepository

  1.  public interface IRepository<T>
  2.     {
  3.         void Add(T entity);
  4.         void Delete(T entity);
  5.     }

Now create the IProfileRepository

  1.     public interface IProfileRepository : IRepository<Profile>
  2.     {
  3.     }

Then create the Repository Class , this is the Generic Class that we talk about

  1.     public class Repository<T> : IRepository<T>
  2.     {
  3.         public void Add(T entity)
  4.         {
  5.             throw new NotImplementedException();
  6.         }
  7.  
  8.         public void Delete(T entity)
  9.         {
  10.             throw new NotImplementedException();
  11.         }
  12.     }

As you see you have to implement the Add and Delete methods, now if you want to create the ProfileRepository you don’t need to create the Delete and Add again

  1.     public class ProfileRepository : Repository<Profile>, IProfileRepository
  2.     {
  3.     }

 That's it, Thanks for reading!


Tags: Design Pattern C#


comments powered by Disqus