Design Mode-Adapter Mode)
What is the adapter mode?
The Adapter mode enables the classes that cannot work together due to incompatibility of interfaces to work together.
Simply put, the things we need are in front of us and cannot be used, but cannot be modified in a short time. So we can find a way to adapt to it. The adapter mode is mainly used to reuse some existing classes, but the interfaces are inconsistent with the requirements of the Reuse Environment.
Sample Code:
////// Define the interface the client expects ///Public class Target {////// Use virtual modifier so that sub-classes can be rewritten ///Public virtual void Request () {Console. WriteLine (This is a common request );}}////// Define the class to be adapted ///Public class Adaptee {public void SpecificRequest () {Console. WriteLine (This is a special request .);}}////// Define the adapter ///Public class Adapter: Target {// create a private Adeptee object private Adaptee adaptee = new Adaptee ();////// By rewriting, the actual call of SpecificRequest () is converted by calling the Request () method ()///Public override void Request () {adaptee. specificRequest () ;}}// client code class Program {static void Main (string [] args) {// for the client, the Target Request () is called () target target = new Adapter (); target. request (); Console. read ();}}
Applicable scenarios: 1. The system needs to use existing classes, and the interfaces of these classes do not conform to the system interfaces.
2. Create a reusable class for some classes that are not highly correlated with each other, including some classes that may be introduced in the future.
3. When two classes do the same or similar things but have different interfaces.
4. The class developed by the old system has implemented some functions, but the client can only access it in the form of another interface, but we do not want to manually change the original class.
5. Use third-party components. The definition of component interfaces is different from that of custom components. You do not want to modify your own interfaces, but use the functions of third-party component interfaces.