C # Basic Series--a romantic encounter: interfaces and abstract classes

Source: Internet
Author: User

Foreword: Recently a friend of acquaintance is ready to switch to do programming, watch his own while watching video learning, very energetic. That day he asked me the interface and abstract class two things, he said, since they are so similar, I can solve the problem with the abstract class, and the whole interface out of what to do, this is not misleading beginners. Bo Master lol, think back to the original self, not also have this kind of doubts ... Today intends to address his problems, combined with a practical use of the scenario to illustrate the similarities and differences between the abstract class and interface, in the end what needs to use the interface? What are some of the things that you need to use abstract classes?

C # Basic Series Catalog:

    • C # Basic Series--LINQ to XML read and write XML
    • C # Basic Series-The use of extension methods
    • C # Basic Series--Serialization efficiency competition
    • C # Basic Series-Reflection notes
    • C # Basic Series--attribute features use
    • C # Basic Series--small-talk generics
    • C # Basic Series--an explanation of common usage of multithreading
    • C # Basic Series--delegation and design pattern (i)
    • C # Basic Series--delegation and Design pattern (ii)
    • C # Basic Series-No more worrying about the interviewer asking me "events".
    • Basic series of C #--Asynchronous programming: Async and await
First, business scenario introduction.

Bo Master intends to use the original outsourcing in Huawei a scenario: We do a device for Huawei inside a collection of equipment usage, the type of equipment, a variety of device login and logoff is basically the same, but each device collection of rules are not the same. The general scenario is that, let's look at the code.

Second, code example

Based on the business scenario, let's simply build the code and take a look at the code structure diagram:

Estm. Spider: The entry procedure for the project, just for testing, here is a simple console program.

Estm. Spider.huawei: Huawei Equipment Acquisition rules, define interface abstraction implementation and concrete implementation.

Estm. Utility: Tool classes and interfaces for the solution.

Here's a look at the specific implementation code:

1. Tool class
namespaceestm. utility{ Public classLoginuser { Public stringUsername {Set;Get; }  Public stringPassword {Set;Get; } }     Public classDevice { Public stringDeviceType {Set;Get; }  Public intWaitsecond {Set;Get; } }}
2. Interface design: ISpider.cs
namespace estm. utility{    // Acquisition Interface, defining the rules for collection public    interface  ispider    {         BOOL Login (Loginuser ologinuser);         string Spider (Device odevice);         void loginout ();    }}
3. Interface abstract Implementation class: SpiderBase.cs
 // <summary>    ///Public Collection base class/// </summary>     Public Abstract classSpiderbase:ispider {//Huawei devices are signed in with Telnet mode. The unified user name password is admin.          Public Virtual BOOLLogin (Loginuser ologinuser) {Console.WriteLine ("The Huawei device is logged in with Telnet mode. "); varBRes =false; if(Ologinuser.username = ="Admin"&& Ologinuser.password = ="Admin") {Console.WriteLine ("User name password check correct, login successful"); BRes=true; }            Else{Console.WriteLine ("User name password check error, Login failed"); }            returnBRes; }        //the acquisition operation is related to the specific device type, where an abstract method is required to require subclasses to override         Public Abstract stringSpider (Device odevice); //Huawei Equipment Unified Logoff         Public Virtual voidLoginout () {Console.WriteLine ("Huawei device is logged off with Telnet"); }    }
4, interface specific implementation class
[Export ("MML",typeof(Ispider))]  Public classSpidermml:spiderbase {//MML Equipment Acquisition         Public Override stringSpider (Device odevice) {Console.WriteLine ("MML Equipment Start acquisition"); return "MML"; }    }
[Export ("TL2",typeof(Ispider))]  Public classSpidertl2:spiderbase {//TL2 Equipment Acquisition         Public Override stringSpider (Device odevice) {Console.WriteLine ("TL2 Equipment Start acquisition"); return "TL2"; }    }
5. Call in console
classProgram {[Import ("MML",typeof(Ispider))]  PublicIspider Spider {Set;Get; } Static voidMain (string[] args) {            varOprogram =NewProgram ();            REGISTERMEF (Oprogram); OProgram.spider.Login (NewLoginuser () {Username ="Admin", Password ="Admin" }); OProgram.spider.Spider (NewDevice () {DeviceType ="Huaweidevice", Waitsecond = - });        OProgram.spider.LoginOut (); }        #regionRegister MEFPrivate Static voidREGISTERMEF (Objectobj) {Aggregatecatalog Aggregatecatalog=NewAggregatecatalog (); varthisassembly =NewDirectorycatalog (AppDomain.CurrentDomain.BaseDirectory,"*.dll");            AGGREGATECATALOG.CATALOGS.ADD (thisassembly); var_container =NewCompositioncontainer (Aggregatecatalog,true);        _container.composeparts (obj); }         #endregion    }
6. Description

This is a more typical application scenario. Interface definition rules, abstract classes define public implementations or abstract methods, and concrete subclasses implement or override abstract class methods. Let's focus on the middle bridge here-abstract class. We know that abstract classes can have either a method of implementation or an abstract method that is not implemented.

(1) Here, the Login, Loginout method because the subclass is common with the same logical method, so we need to implement these two methods in the abstract class, if the subclass does not have special needs, the invocation of the method of the parent class directly, if the subclass has special needs, You can override the parent class's methods. This design improves both the code reuse rate and the flexibility to replicate.

(2) On the other hand, abstract class also defines the abstract method, the role of this abstract method here is very good embodiment: if the subclass does not rewrite the parent class abstract method, compile pass, direct error. This requires that our subclasses have to override the abstract method. From this point, the methods of abstract methods and interfaces differ little.

(3) If there is no abstract class, use an ordinary class instead of a row? The blogger's answer is: OK! But not good! If you have to say, I am using an ordinary class, the public abstract string Spider (Device odevice); This method is written as

 Public Virtual string Spider (Device odevice) {      return"";  }

Seemingly no problem, anyway subclasses to rewrite. Sure, this design is fine, but what if you accidentally forgot to override it? The program will still run and may error when running. Since Microsoft has provided us with an abstract such a thing, why don't we use it.

Third, Code extension

The need for and use of our abstract class is described above. Then the next new question, perhaps someone asked, you said that the BA Ba Ba said so much, nothing more than to say the necessity of abstract class, then since the abstract class so useful, we directly with the abstract class is good, why do you want to get an interface? Speaking of this, we should talk about interface-oriented programming. In fact, interface-oriented programming and object-oriented programming is not lateral, it is not a more advanced object-oriented programming idea of a separate, but attached to the object-oriented ideology, belongs to its part. Or, it is one of the essence of thought in object-oriented programming system. Before the blogger's article shared the meaning of interface-oriented programming: dependency inversion, loose coupling. So can there be no interface here, directly in the abstract class instead? The answer is still OK! But not good!

For example, we now come to the new demand, ZTE will also use our acquisition system, but its device type, login logout mode and Huawei equipment is very different. So this time the meaning of our interface is reflected, if we use the interface, we only need to rewrite a ESTM.Spider.Huawei this project is good, we are called ESTM.Spider.Zhongxing. Let's take a look at:

The code is as follows:

namespaceestm. spider.zhongxing{/// <summary>    ///ZTE Equipment Collection base class/// </summary>     Public Abstract classSpiderbase:ispider {//ZTE Device Universal Login Method         Public Virtual BOOLLogin (Loginuser ologinuser) {Console.WriteLine ("ZTE Device Login before a more data check: ....."); Console.WriteLine ("ZTE devices use WMI to log in. "); varBRes =false; if(Ologinuser.username = ="Root"&& Ologinuser.password = ="Root") {Console.WriteLine ("User name password check correct, login successful"); BRes=true; }            Else{Console.WriteLine ("User name password check error, Login failed"); }            returnBRes; }        //defines an abstract method that requires subclasses to override         Public Abstract stringSpider (Device odevice); //ZTE Equipment General logoff         Public Virtual voidLoginout () {Console.WriteLine ("ZTE Device is logged off with WMI"); }    }}
namespaceestm. spider.zhongxing{[Export ("ZXGC",typeof(Ispider))]  Public classSpiderzxgc:spiderbase { Public Override stringSpider (Utility.device odevice) {Console.WriteLine ("ZTE ZXGC Equipment began to collect"); return "ZXGC"; }    }}
namespaceestm. spider.zhongxing{[Export ("zxgy",typeof(Ispider))]  Public classSpiderzxgy:spiderbase { Public Override stringSpider (Utility.device odevice) {Console.WriteLine ("ZTE Zxgy Equipment began to collect"); return "zxgy"; }    }}

Because of the interface here, we will ESTM.Spider.Zhongxing this project after the completion of the development of the DLL, put the DLL into the console program, directly through the MEF to import different sub-class objects can be used, do not need to change the console of most things. If you use an abstract class instead of an interface, most of the code in the console has to be changed, and the console program relies on multiple DLLs, which is also detrimental to the design's loose coupling. Bo Master here in order to simple, with the MEF to simple import, in fact, the formal project, should be used in the factory using reflection directly create concrete examples.

Iv. Summary

1, the interface is a set of rules, it is mainly defined by the rules of things, embodies the type, you must have the concept of these rules. Its purpose is mainly to rely on inversion and loose coupling, from this point, the interface can not be omitted or replaced with abstract classes. In summary, interfaces and abstract classes are not the same.

2, abstract class is mainly used for public implementation and constrained subclasses must be rewritten. Using the above example, Login, loginout for public implementation, improved code reuse, spider for abstraction, constrained subclasses must rewrite the Spider method. That's why you can't use ordinary classes here.

3. Summarize the differences between interfaces and abstract classes in a nutshell: The use of abstract classes is for code reuse, and the motivation for using interfaces is to achieve polymorphism (dependency inversion). As for the use of the interface or abstract class, see the specific situation.

C # Basic Series--a romantic encounter: interfaces and abstract classes

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.