2.2 framework communication contract-Interface

Source: Internet
Author: User

after the agent framework host Program is started, it first traverses all the plug-in assembly in the plug-in folder. These assembly files exist in the DLL format, the framework Host Program traverses the plug-in types contained in the set, and then the plug-in engine generates the icommand , itool , itoolbar , imenu and idockablewindow and other objects. These objects are stored in a plug-in Object pool and passed to the Host Program for further parsing and processing.

A plug-in set can contain multiple plug-in types (that is, multipleClassOrStructCodeFiles can be compiled in oneAssemblyFile), how does the framework Host Program identify these types of objects as plug-in objects? This is because each plug-in object has an identity -- interface, this identifier is called a "Communication Contract" in the Framework Design -- Because interfaces can also be seen as a type and define necessary methods and attributes, the host program can use this contract to generate a specificUIObject and event response to external operations. The Host Program must declare the functions that can be called by the plug-in, and the plug-in must meet the requirements to be used by the Host Program; otherwise, the plug-in also needs to know the functions and Attributes provided by the Host Program to integrate itself into the structure of the Host Program.

As a high-aggregation and Low-coupling system, the plug-in framework is separated between its function definition and function implementation. This policy guarantees the high aggregation implementation. A plug-in framework is like a function aggregation station. It announces to the outside that any component that complies with the plug-in specifications it releases (the class that implements interfaces is usually called a component) can be added to this platform, the specific functions of these components are not concerned. Of course, the framework also provides necessary information and help to ensure that these components can implement their functions normally.

Communication contracts can appear in the form of interfaces or abstract classes, but generally interfaces are used. This is a typical bridge (Bridge) Mode. The bridge mode is an accepted way of expressing the definition and its associated implementation (Factory) Mode provides the foundation for all applications. Components developed using the bridge mode have the advantage of multiple parties working collaboratively for a common purpose without having to interact with each other except some interfaces that must be implemented.[1]

In the structure design with multiple logic layers, communication between layers is mostly implemented through interfaces, because interfaces are not easily changed. If the functions of one layer Change, other layers are not affected; as long as the interface component functions normally, the program runs normally. This approach minimizes the interaction between layers.

2.2.1. Interface secret

In most programming and design work, it is rare to consider "interfaces (Interface) "If we only meet the requirement of using the Drag Control inIDEProgramming and use on. NET FrameworkA general class library may never use interfaces in the program, even ifC #Readers will see this term countless times in object-oriented language grammar books.

Interface exists as a Type

The interface is of the type (Class) Definitions and contracts of common behaviors. For example, all transportation tools include methods such as start, stop, acceleration, and brake (Vehicleclass) These general and public methods can be defined in an interface, and these operations may be different between different types of vehicles, however, interfaces do not consider the differences between the methods they adopt to implement their own functions or methods. They only care that all these types must implement all functions defined by interfaces, the type of the interface can be considered as a transportation tool.

Therefore, the two main functions of an interface are:

LDefine public methods and attributes required for multiple types;

LAs a non-instantiated type;

The class or structure that implements the interface must implement every attribute and method defined in the interface. These methods are usually related in design or function, which is the most typical interface design strategy.

Interface and abstract class

Interfaces are very similar to abstract classes. For example, neither of them can generate instance objects, but both can be used as a contract and definition. However, interfaces and abstract classes are essentially different. These differences include:

LThe interface does not have any implementation part, but the abstract class can contain some implementation code;

LThe interface has no fields, but the abstract class can contain fields;

LInterface can be structured (Struct), But the abstract class does not work;

LAbstract classes include constructors and destructor;

LInterfaces can only inherit from interfaces, while abstract classes can inherit from other classes and interfaces;

LInterfaces support multiple inheritance While abstract classes only support single inheritance.

The following is a comparison between interfaces and abstract classes:

InterfaceIiterface:

Public interface iinterface {

Void methoda (int );

Void methodb (int );

Void methodc (int );

Void methodd (int );

}

Abstract classAclass:

Public abstract class Aclass {

Abstract Public void methoda (int );

Abstract Public void methodb (int );

Abstract Public void methodc (int );

Abstract Public void methodd (int );

}

The interface cannot include Operator overloading because it is not impossible to implement it. Because the interface is a public contract, it will be published to other types of languages. For exampleVB. NETSuch languages do not support Operator overloading. Implementing Operator Overloading in interfaces may cause compatibility problems between different languages.

The interface definition members cannot have modifiers either, because the interface itself isPublicIt requires that its members be public. Otherwise, such an interface has no meaning and the contract that is not published is useless. If you must add a modifier before the interface member, it will cause a compiler error.

Multi-inheritance is not the reason for interface existence

Even from the perspective of the bridge mode, there is another important reason for many object-oriented languages to introduce interfaces: one class can implement multiple interfaces.

In most object-oriented languages, multiple inheritance is forbidden, because when the compiler needs to find the virtual method (Virtual Method), The compiler does not know which base class the virtual method points to during execution. But the interface does not, even if a type implements multiple interfaces, there is no uncertainty.

An interface is also a type. Like an abstract class, it can be regarded as a type that cannot be instantiated. Therefore, an object can be considered as multiple types by implementing multiple interfaces. For example, if you want to abstract an amphibious vehicle, in the product registration directory, will it be attributed to a vehicle or a ship? Obviously, it is difficult for a single Inheritance Mechanism to describe this structure. We cannot make the amphibious vehicle type inherit from two base classes at the same time, while the vehicle type and ship type have no inheritance relationship, this vehicle cannot be attributed to the correct product catalog by means of multi-level inheritance.

This problem can be avoided by using interfaces. we can define a vehicle interface (Ibusinterface) And a ship interface (IshipinterfaceBut the amphibious vehicle type only needs to implement these two interfaces at the same time. In this way, it can be regarded as either a vehicle type or a ship type.

In the above example, the interface shows an important advantage in replacing multiple inheritance, but does it mean that the interface was proposed by the object-oriented language designer for this purpose?

By no means, the implementation of interfaces is not similar (Class), It is not a substitute for multiple inheritance mechanisms.

We often confuse interfaces with abstract classes. In fact, they are essentially different: interfaces are used to define the contract for communication between two objects, while abstract classes are used to encapsulate the common behavior between objects; abstract classes should be mainly used in groups with inheritance relationships, and interfaces are most suitable for providing mutual adjustment methods for irrelevant classes.

Interfaces and abstract classes have different goals at the beginning of the design, but they are often misunderstood by many readers in practical applications. This difference is embodied in the design of many Component Libraries: Different Types of components call each other through interfaces, while the same type of components, suchColorClasses are organized together through abstract classes, that is, interfaces communicate externally, and abstract classes are organized internally.

Suggestions on Interface Usage

InMsdnThe following suggestions on interfaces and abstract classes are provided:

LIf you want to create multiple versions of a component, create an abstract class. Abstract classes provide a simple way to control component versions. By updating the base class, all inheritance classes are automatically updated with the change. On the other hand, the interface cannot be changed once it is created. If you need a new version of the interface, you must create a new interface.

LIf the created function is used across a wide range of different objects, the interface is used. Abstract classes are mainly used for closely related objects, and interfaces are most suitable for providing general functions for irrelevant classes.

LIf you want to design small and concise functional blocks, use interfaces. If you want to design a large functional unit, use an abstract class.

LIf you want to provide common implemented functions among all the implementations of a component, use an abstract class. Abstract classes allow partial implementation classes, while interfaces do not include the implementation of any member.

This API is not an API

YesComDevelopers with component coding experience must note that,C #AndComDifferent interfaces, the former does not need to support anyComInfrastructure, suchC #The interface in is not derived fromIunknownInterface, it does notGuid. But they all share a common feature, that is, providing contracts rather than implementing them.

2.2.2. Implementation interface and explicit implementation Interface

The implementation of the interface looks very simple and can be completed as follows (C #Is usedPascalNaming style.IId Interface ):

Public interface IA

{

Void run ();

}

Public class CA: IA

{

# Region IAMember

Public void run ()

{

System. Console. writeline ("ca ");

}

# Endregion

}

If you are usingVs2005Tool. When implementing the interface, a selection item "implementation interface" will pop up.IAOr explicitly implement the interfaceIA", The implementation interface looks very simple, but what is" explicit implementation?

Modify the interface definition code above and add a new interfaceIB:

Public interface IA

{

Void run ();

}

Public interface IB

{

Void run ();

}

Two interfacesIAAndIBAll have a same nameRunMethod exists. modify the code to make the typeCAImplement them, whereIBExplicit implementation:

Public class CA: IA, IB

{

# Region IAMember

Public void run ()

{

System. Console. writeline ("IA. Run ");

}

# Endregion

# Region IBMember

Void Ib. Run ()

{

System. Console. writeline ("IB. Run ");

}

# Endregion

}

We will find thatCAImplementationIA,IBIfIAThe interface is implemented,IBThe interface can only be explicitly implemented, orIAAndIBAll interfaces are implemented explicitly. Otherwise, a compilation error occurs. Test nowCATo see the difference:

Public static void main ()

{

CA = new CA ();

CA. Run ();

Ia = Ca;

IA. Run ();

IB = Ca;

Ib. Run ();

}

The test results are as follows:

IA. Run

IA. Run

Ib. Run

As you can see, if it is a direct access type, itsRunThe method isIAInstead of explicitly implementing the interface.IB.

The explicit implementation interface has the following features:

LYou cannot use full names to access the code of explicit interface members in method call, attribute access, and index indicator access. The explicit interface member execution body can only be accessed through class instances that implement the interface, for example, only throughIBInterface access;

LThe execution body of an explicit interface member cannot use or add any access restriction characters.Abstract, virtual, overrideOrStaticModifier;

LThe explicit interface member execution body has different access methods than other members. Because it cannot be accessed by full name in method call, attribute access, and index indicator access, the explicit interface member execution body is private in a sense. However, they can also be accessed through interface instances and have a certain public nature;

LOnly when a class is defined, the interface name is written in the base class list, and the full name, type, and return type defined in the class are completely consistent with the explicit interface member execution body, the explicit interface member execution body is valid.

Generally, an explicit interface member execution body has two purposes:

First, the explicit interface member execution body cannot be accessed through the full name of the class, so that the interface implementation part can be separately separated from the public interface, if all the methods of a class are implemented explicitly, this class will not be able to call its contained methods by class instantiation, but can only be accessed by interface definition. If a class only uses this interface internally, the external caller of the class will not be able to directly access this interface. This explicit interface member execution body can only serve internally.

The explicit interface member execution body avoids confusion between multiple interface members due to the same name. If a class wants to adopt different implementation methods for interface members with the same name and return type, it must use the explicit interface member execution body. If there is no explicit interface member execution body, the class cannot be implemented for interface members of different names and return types. We can modifyIATo add a method with different return values and parameters.RunFunction.CAImplementation InterfaceIAIt must be implemented explicitly.

 

IfClassTwo interfaces are implemented, and both interfaces contain methods with the same signature. Implementing this method in the class will result in the two interfaces using the same method as their definition implementation. If twoInterfaceWhen a member executes different functions, the implementation of one or both interfaces may be incorrect. In this case, the interface members must be explicitly implemented.

In short, an explicit implementation Interface contains two capabilities: generate a contract that is only used within a certain range and use the same method to distinguish different interfaces implemented by a class.



[1]Christian gross,. net2.0Pattern development practices Beijing: People's post and telecommunications Publishing House2007 p57

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.