Both the delegate and interface allow the class designer to separate the type declaration and implementation. Any Or Can inherit and implement the given . Can be created for methods in any class The premise is that the method meets the signature of the delegate method. Interface references or delegation can be used by objects that do not understand the classes that implement this interface or delegate methods. Since these similarities exist, when should the class designer use the delegate and when should the interface be used?
Use delegation in the following cases:
When the event design mode is used.
When static methods are encapsulated.
When the caller does not need to access other attributes, methods, or interfaces in the objects that implement the method.
A convenient combination.
When the class may require multiple implementations of this method.
Use the interface in the following cases:
When there is a set of methods that may be called.
When the class only needs a single implementation of the method.
When the class using the interface wants to forcibly convert the interface to another interface or class type.
When the implemented method is linked to the type or identifier of the class: for example, compare the method.
A good example of using a single method interface without delegation is: or generic version . icomparable statement method. This method returns an integer that specifies the relationship between two objects of the same type, namely, less than, equal to, or greater. icomparable can be used as the basis for sorting algorithms . Although it is effective to use the delegated comparison method as the basis for sorting algorithms, It is not ideal. Because the comparison capability belongs to the class, and the comparison algorithm does not change at runtime, a single method interface is ideal.