C # "Let's Talk About polymorphism" -- use polymorphism in the logic layer BLL,

Source: Internet
Author: User

C # "Let's Talk About polymorphism" -- use polymorphism in the logic layer BLL,

This article is copyrighted by the bloggers and the author Wu Shuang himself. Welcome to repost, repost and crawler please note the original address http://www.cnblogs.com/tdws/p/5861842.html

Last night, a friend said that he had learned for a long time and still did not understand polymorphism. Let me explain it briefly. I think polymorphism is the simplest and the most difficult among the three features that many people think about. It is the seemingly easy encapsulation. When writing object-oriented code, how to make the code more readable, in addition to the variables and method naming standards, do only one thing to do in a method, this idea is the main idea in the book "clean code". In fact, experienced users want to see the code in a short, maintainable, and readable manner, I believe everyone is lucky to have met hundreds of thousands of lines of code. More importantly, a friend once maintained tens of thousands of lines of Action, it takes three days to debug and pass the logic. Some people say this is caused by the increasing business logic. But I think that in this case, we should try our best to do one thing in one way. I don't have much to worry about. The code is neat. When I was in my junior year, I "spoke" over http://www.cnblogs.com/tdws/p/4674489.html.

Encapsulation is not the topic of today. Today we are talking about polymorphism. When a friend asked me, I gave him the following short example.

In general, in this example, two classes of AdminDal and UserDal are created at the DAL layer in the basic three-tier architecture. In both classes, there are methods for adding objects and deleting objects. At this time, we should abstract the two classes into a parent class BaseDal <T>, the parent class is their public method, and the parent class needs a generic T, so that the method of the parent class can understand the type of the object you want to add or delete. See the following code. Although the public methods of the two classes are in the parent class, their own unique methods should be written in their own Dal layer.

1   public class UserDal: BaseDal<UserEntity>2   {3         4   }
1 public class AdminDal: BaseDal <AdminEntity> 2 {3 public void Manage () 4 {5 Console. WriteLine ("administrator management website"); 6} 7}
1 public class BaseDal <T> 2 {3 public void AddObj (T obj) 4 {5 Console. writeLine ("Object added successfully, object belongs to" + obj. getType (). toString (); 6} 7 8 public void DeleteObj (T obj) 9 {10 Console. writeLine ("the object is successfully deleted, and the object belongs to" + obj. getType (). toString (); 11} 12 13}

The logic layer code is given below. If you say that your code may be like this during normal development.

 1  public class UserBll  2     { 3         UserDal dal = new UserDal(); 4  5         public void Add(UserEntity obj) 6         { 7             dal.AddObj(obj); 8         } 9 10         public void Delete(UserEntity obj)11         {12             dal.DeleteObj(obj);13         }14      }
    public class AdminBll 
{ AdminDal dal = new AdminDal(); public void Add(AdminEntity admin) { dal.AddObj(admin); } public void Delete(AdminEntity admin) { dal.DeleteObj(admin); } public void Manage() { dal.Manage(); } }

That is, the dal layer is called in the respective logic layers. At this time, you can see that there are still so many duplicate codes, should they be encapsulated into a BaseBll again <T>. The answer is yes, but the question comes again. In the process of encapsulating the parent class, you will find that how is the dal object encapsulated? This is the key point of using polymorphism. Let's take a look at the BaseBll. cs code.

 public abstract class BaseBll<T> where T:class, new()    {        public BaseDal<T> currentDal;        public BaseBll()        {            SetCurrentDal();        }        public abstract void SetCurrentDal();        public void BaseAdd(T obj)        {            currentDal.AddObj(obj);        }        public void BaseDelete(T obj)        {            currentDal.DeleteObj(obj);        }    }

I gave an abstract base class and defined the abstract SetCurrentDal method. This method is used to set whether the currentDal of the current class is adminDal or userDal. We call the SetCurrentDal abstract method in the constructor. Why is it called in the constructor? when instantiating a subclass object, it must first enter the constructor of its parent class. When the sub-classes AdminBll and UserBll inherit BaseBll <T>, you must override the abstract method and set the actual value for the BaseDal <T> currentDal object. I will first give the subclass code

 1 public class AdminBll : BaseBll<AdminEntity> 2     { 3         AdminDal dal = new AdminDal(); 4         public AdminBll() 5         { 6  7         } 8         public void Manage() 9         {10             new AdminDal().Manage();11         }12 13         public override void SetCurrentDal()14         {15             currentDal = new AdminDal();16         }17     }
1 public class UserBll : BaseBll<UserEntity>2     {3         public override void SetCurrentDal()4         {5             base.currentDal = new UserDal();6         }7     }

When instantiating a subclass object, the process is: subclass Constructor (not entered) -Go to the parent class constructor-the parent class constructor to call the SetCurrentDal rewritten by the subclass (the instance of the current polymorphism currentDal)-the execution of the parent class constructor is complete (the currentDal setting is complete) -subclass constructor. This is the polymorphism of abstract methods.

The following is a call at the UI Layer to see the result:

1 class Program 2 {3 static void Main (string [] args) 4 {5 AdminBll adminBll = new AdminBll (); 6 AdminEntity admin = new AdminEntity () {AdminName = "Wu Shuang", AdminPwd = "123"}; 7 adminBll. manage (); 8 adminBll. baseAdd (admin); 9 Console. readKey (); 10} 11}

Output result:

 

During development, you may have many entity classes. Each entity class has its own common methods such as addition, deletion, modification, and query. Based on this situation, we need a means to encapsulate it. The reason why polymorphism is used in the logic layer is that when we encapsulate the parent class, we are not sure whether the current currentDal is adminDal, userDal, or xxxDal. To encapsulate the base class, this polymorphism object is essential.

Of course, in practice, if you are writing native SQL, this encapsulation is really not easy, and various concatenated SQL statements. But if you use the ORM framework, EF, Dapper, and so on, this method is really essential. You may add the interface layer, the work unit, and the object creation is not new, use Abstract Factory and dependency injection. In any case, the polymorphism of this layer can be used, but the object creation is slightly modified.

 

In the next stage, we plan to share the background architecture. MVC WebApi + EF/Dapper + unit of work + Abstract Factory/dependency injection Autofac + AutoMapper + Log component.

I have also set up such a framework in projects many times, in terms of cache performance improvement, processing high concurrency, application server cluster, cache cluster, queue cluster, etc, this will also be added to the sharing.

 

If you want to share your feedback today, please click here to help you, and also like your progress.

Click follow below to make progress together.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.