Interface Programming helps meet the "low coupling" requirements in object-oriented development and design.
For example, a company has a special printer that can be used for one year. A year later, it may be used as another printer. Both printers are special and expensive.ProgramIf you want to change the printer, a few modifications will be available.
Method:
1. Define a printer interface.
2. Define printer Class A and Class B to implement this interface respectively.
3. Define a factory class. in the class, you can choose to return the interfaces implemented by a or implemented by B.
4. When using a printer in a program, you can use the factory class to call the printer without knowing what the printer is.
If the printer is changed, you only need to modify the factory class. if the printer has been called in one thousand locations, you do not need to modify it one by one. just modify a place. interface acts as an isolation layer.
// Define the printer interface
Interface iPrint
{
Bool printdata (string data );
}
// Define printer Class A and implement the interface (inherited)
Class printa: iPrint
{
Public Virtual bool printdata (string data)
{
// The specific business logic is omitted
}
}
Defines printer Class B and implements the interface (inherited)
Class printb: iPrint
{
Public Virtual bool printdata (string data)
{
// The specific business logic is omitted
}
}
// Define the factory class
Class printfactory {
Public iPrint createprint ()
{
// Return an interface implemented by the host Class A or B, such
Return new printa ();
}
}
// Call the printer through the factory class
Private void button#click (Object sender, eventargs E)
{
Printfactory myfactory = new printfactory ();
IPrint myprint = myfactory. createprint ();
Myprint. printdata ("this is very convenient ");