Original address: http://www.php.cn/
Suppose our company has two kinds of programmers: VB programmer, refers to use VB to write program programmer, with Clsvbprogramer This class, Delphi programmer refers to use Delphi to write program programmer, with Clsdelphiprogramer this class to express. Each class has a Writecode () method. Defined as follows:
Class Clsvbprogramer () {.... Writecode () { //write code in VB language;} Class Clsdelphiprogramer () {.... Writecode () { //write code in Delphi language;}
Now the company has a project that requires a programmer to write a program.
Class Clsproject () {.... Writeprograme (Clsvbprogramer programer)//VB Write code { Programer. Writecode ();} Writeprograme (Clsdelphiprogramer programer)//Overloaded method, with Delphi write code { Programer. Writecode ();} ......}
In the main program we can write this:
Main () { clsproject proj=new clsproject; If need to write code with VB clsvbprogramer programer1=new clsvbprogramer; Proj. Writeprograme (programer1); If you need to write code with Delphi Clsdelphiprogramer programer2=new Clsdelphiprogramer; Proj. Writeprograme (PROGRAMER2);}
But if the company came to a C # programmer, how do we change the program so that it can implement the function of writing programs in C #? We need to add a new class Clscsharpprogramer, and Clsproject this class again to reload the Writeprograme (Clscsharpprogramer programer) method. It's a lot of trouble. If there are C programmers, C + + programmers, Java programmers. It's too much trouble!
But if you switch to an interface, it's completely different:
First declare a programmer interface:
Interface Iprogramer () {Writecode ();} Then declare two classes and implement the Iprogramer interface: Class Clsvbprogramer (): iprogramer{.... Writecode () { //write code in VB language;}
Class Clsdelphiprogramer (): iprogramer{.... Writecode () { //write code in Delphi language;}
Make a change to the Clsproject class:
Class Clsproject () {.... Writeprograme (Iprogramer programer) { programer. Writecode ();//Write Code} ...} Main () { clsproject proj=new clsproject; Iprogramer Programer; If need to write code with VB programer=new Clsvbprogramer; Proj. Writeprograme (programer); If need to use Delphi write code programer=new Clsdelphiprogramer; Proj. Writeprograme (Programer); }
If any more programmers like C#,c,c++,java are added, we just need to add their related classes and then make a slight change in main (). Extensibility is particularly good!
In addition, if we clsproject this class into a component, then when our users need to expand the function, we only need to make a small external changes can be achieved, we can say there is no need to change the components we have sealed! is not very convenient, very powerful!
The above is the role of C # interface in-depth understanding of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!