C # interface function (original title) Suppose our company has two types of programmers: VB programmers, who refer to programmers who write programs using VB and are represented by clsvbprogramer; delphi programmers refer to programmers who use Delphi to write programs and use clsdelphiprogramer to represent them. Each class has a writecode () method. Definition:
Class clsvbprogramer ()
{
....
Writecode ()
{
// Write code in VB;
}
....
}
Class clsdelphiprogramer ()
{
....
Writecode ()
{
// Write the code in Delphi;
}
....
}
Now the company has a project that requires a programmer to write a program.
Class clsproject ()
{
....
Writeprograme (clsvbprogramer programer) // write code with VB
{
Programer. writecode ();
}
Writeprograme (clsdelphiprogramer programer) // reload method, use Delphi to write code
{
Programer. writecode ();
}
......
}
In the main program, we can write as follows:
Main ()
{
Clsproject proj = new clsproject;
// Use VB to write code
Clsvbprogramer programer1 = new clsvbprogramer;
Proj. writeprograme (programer1 );
// Use Delphi to write code
Clsdelphiprogramer programer2 = new clsdelphiprogramer;
Proj. WritePrograme (programer2 );
}
However, if the company has another C # programmer, how can we modify this program so that it can implement the function of writing a program using C? We need to add a new clsCSharpProgramer class, and re-load the WritePrograme (clsCSharpProgramer programer) method in this clsProject class. This is a lot of trouble. If there are still C programmers, C ++ programmers, and JAVA programmers. It's too much trouble!
However, if you use an interface, it will be totally 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;
}
....
}
Class clsDelphiProgramer (): IProgramer
{
....
WriteCode ()
{
// Write the code in Delphi;
}
....
}
Modify the clsproject class as follows:
Class clsproject ()
{
....
Writeprograme (iprogramer programer)
{
Programer. writecode (); // write code
}
......
}
Main ()
{
Clsproject proj = new clsproject;
Iprogramer programer;
// Use VB to write code
Programer = new clsvbprogramer;
Proj. writeprograme (programer );
// Use Delphi to write code
Programer = new clsDelphiProgramer;
Proj. WritePrograme (programer );
}
If programmers such as C #, C, C ++, and JAVA are added, we only need to add their related classes, and then add them in main () and then click OK. Great scalability!
In addition, if we encapsulate the clsProject class into a component, when our users need to expand the function, we only need to make small modifications externally, it can be said that there is no need to modify the components we have already closed! Is it very convenient and powerful!