Objective C # Reading Notes-entry 22: replace inheritance by defining and implementing Interfaces

Source: Internet
Author: User

An interface is a contract-based design. A type must implement the methods defined in the interface. Abstract base classes provide a common abstraction for a group of related types. Pay attention to the usage scenarios and differences between the two: The base class describes what the object is and the interface describes how the object will behave.

 

1. Interface

An interface describes a set of functions. It is a contract. The type of any implemented interface must provide specific implementation for all elements defined in the interface.. We should extract reusable behaviors and define them in Interfaces. Since different types can implement an interface, this will increaseCode. For developers themselves, implementing interfaces is easier than inheriting custom base classes.

2. abstract base classes

Abstract base classes not only describe common behaviors, but also provide specific implementations for the derived classes (for subclasses, generic and reusable code). Abstract base classes can provide an implementation for any specific behavior, while interfaces cannot. This method of implementation reuse provides us with another benefit:When you expand system functions, you can add and implement a function to the base class. All Derived classes have this function immediately and add a member to the interface, all classes that implement this interface will be destroyed..

 

3. Use interfaces to replace inheritance

Using abstract base classes or interfacesRepresents two different attitudes towards future changes.:Encapsulate a set of functions in one interface as implementation contracts of other types. The base class can be extended in the future, and these extensions will automatically become part of the subclass..

 

3.1 simulate inheritance using extension methods

In fact, these two methods can be used together, that is, the type can support multiple interfaces and reuse them. We know that an interface cannot contain an implementation or any specific data member. However,The extension method can be applied to interfaces.. For example:System. LINQ. enumerableClass contains more than 30 declarationsIenumerable <t>Interface extension method,All types that implement this interface automatically obtain the implementation of these extension methods (Note: The interface itself cannot contain any implementation, but it only provides some implementation through simulation in the form of extension methods). For example, the following extension method for the ienumerable interface:

 1   Public   Static   Class  Extensions  2   {  3        ///  <Summary>  4        ///  Is ienumerable  <T>  Type addition Extension Method  5        ///   </Summary>  6        ///   <Typeparam name = "T"> </typeparam>  7        ///   <Param name = "sequence"> </param>  8       ///   <Param name = "action"> </param>  9        Public   Static   Void Forall <t> ( This Ienumerable <t> sequence, Action <t> Action)  10   {  11            Foreach (T item In  Sequence)  12  {  13   Action (item );  14   }  15   }  16 }

All types that implement the ienumerable interface automatically obtain the implementation of this method. Similarly,If a class implements the ienumerable interface, it also obtains the implementation of all the extension methods of this interface..

 

3.2 flexibility in Interface Programming

In the. NET environment, inheritance is a single inheritance, which is more flexible than programming based on the basic class, because one type can implement multiple interfaces. The same irrelevant type can also implement the same interface,This interface can simplify your work when writing public logic for irrelevant classes.. Let's look at the following example: Assume thatProgramEmployees, customers, and third-party employees need to be managed. These types are irrelevant (from the inheritance system perspective), but they have some public attributes, such as names, addresses, and phone numbers:

View code

1   Public   Class  Employee  2   {  3       Public   String Firstname { Get ; Set  ;}  4       Public   String Lastname { Get ;Set  ;}  5   6       Public   String  Lastname  7   {  8           Get  9   {  10               Return   String . Format ( " {0}, {1}  "  , Lastname, firstname );  11   }  12   }  13       //  ...  14   }  15   16   Public   Class  Customer 17   {  18       Public   String  Lastname  19   {  20           Get  21   {  22               Return  Customername;  23   } 24   }  25       //  ...  26       Private   String  Customername;  27   }  28   29   Public   Class  Vendor  30   { 31       Public   String  Name  32   {  33           Get  34   {  35               Return  Vendorname;  36   }  37   } 38       //  ...  39       Private   String  Vendorname;  40 }

 

The name attribute is shown above, and other attributes are skipped. Now we can abstract public attributes into an interface:

Public InterfaceIcontactinfo {//NameStringName {Get;}//Contact numberPhonenumber primarycontact {Get;}//FaxPhonenumber Fax {Get;}//AddressAddress primaryaddress {Get;}}

 

We will implement the icontactinfo interface for all the above classes:

 
1 //... Other classes ..2 Public ClassEmployee: icontactinfo3 {4//...5}

 

Now we need to write a new method to print our own information for these types:

1 Public VoidPrintmailinglabel (icontactinfo ic)2 {3//...4}

We can see that all the methods can be used as long as they implement the interface type, thanks to putting our public logic in the interface.

At the same time, APIs that define classes using interfaces provide better flexibility. When a type attribute is exposed as a class, all interfaces of the class are exposed. If an interface is exposed, you can choose to provide only the necessary methods and attributes for the user. The Implementation Details of the class attributes that implement this interface may change over time.

 

3.3 avoid unpacking by Using Interfaces in the Structure

The difference between an interface and an abstract base class is that an abstract base class is limited to a reference type, while an interface does not. When we pack struct, The boxed object actually supports all interfaces supported by struct. When you use an interface pointer to access the struct, you do not have to unpack it to access internal data. Example:

 1       Public  Struct Urlinfo: icomparable <urlinfo> , Icomparable  2   {  3           Private   String  URL;  4           Private   String  Description;  5   6           Public   Int Compareto (urlinfo other)  7   {  8               Return  URL. compareto (other. url );  9   }  10   11           # Region Icomparable Member 12   13           Int Icomparable. compareto ( Object  OBJ) 14   {  15               If (OBJ Is  Urlinfo)  16   {  17 Urlinfo Other = (Urlinfo) OBJ;  18                   Return  Compareto (other );  19   }  20              Else  21   {  22                   Throw   New Argumentexception ( "  The compared object is not of the urlinfo type.  "  );  23   }  24   }  25   26           # Endregion 27 }

Because urlinfo implements the icomparable <t> and icomparable interfaces, we can easily create a sort list that protects urlinfo objects. Even the code that relies on the earlier version of icomparable reduces the number of times of packing and unpacking, because the customer code can directly call icomparable. compareto () without unpacking ().

 

Section

An interface is a contractual design: a type that implements an interface must provide all the methods agreed in the interface. Abstract base classes provide a common abstraction for a group of project types. By carefully understanding the differences between the two, we are able to create designs that are more expressive and better able to respond to changes. Use the class hierarchy to define related types, use interfaces to expose functions, and implement these interfaces for different types.

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.