The interface can never be directly instantiated. -- Msdn
But it can be said that this is used
Interface instance = new indicates the class () that implements the interface; it indicates to generate an object of the class that implements the interface.
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 may be used as another printer, both of which are special and expensive. therefore, the current program can be modified with a few changes after changing the printer.
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.
In the object-oriented design, interfaces play an important role,
// Define the printer interface
Interface iPrint ...{
Bool printdata (string data );
}
// Define printer Class A and implement the interface
Class printa: iPrint ...{
Public Virtual bool printdata (string data )...{
// The specific business logic is omitted
}
}
Define printer Class B and implement the interface
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 ");
}
Therefore, it is best to create a factory using interfaces.