23 Design Patterns (9) - Adapter Pattern

Table of contents

1. Basic introduction

Two, demo

2.1, class adapter mode

Class Adapter Pattern Considerations and Details

2.2, object adapter mode

Object Adapter Pattern Considerations and Details

2.3, interface adapter mode

 Interface Adapter Pattern Introduction

Third, the application of the adapter mode in the framework

3.1 Application in SpringMVC framework

3.2. Adapter mode in spring AOP


1. Basic introduction

1) Adapter Pattern (Adapter Pattern) converts the interface of a certain class into another interface representation expected by the client. The main purpose is compatibility, so that two classes that cannot work together due to interface mismatch can work together. Its alias is wrapper (Wrapper)

2) Adapter mode is a structural mode

3) Mainly divided into three categories: class adapter mode, object adapter mode, interface adapter mode

Two, demo

2.1, class adapter mode

Using the example of a charger in life to explain the adapter, the charger itself is equivalent to the Adapter, 220V AC is equivalent to src (that is, the adapter), and our target dst (that is, the target) is 5V DC.

package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:45
 * @Des: 被适配者
 */
public class Voltage220V {

    public int output220V() {
        int src = 220;
        System.out.println("电压:" + src);
        return src;
    }
}
package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:46
 * @Des: 目标
 */
public interface IVoltage5V {
    int output5V();
}
package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:46
 * @Des: 适配器
 */
public class VoltageAdapter extends Voltage220V implements IVoltage5V{
    @Override
    public int output5V() {
        int srcV = output220V();
        int dstV = srcV / 44;
        return dstV;
    }
}
package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:47
 * @Des: 使用者
 */
public class Phone {
    public void charging(IVoltage5V iVoltage5V) {
        if (iVoltage5V.output5V() == 5) {
            System.out.println("电压为5伏可以充电!");
        } else if (iVoltage5V.output5V() > 5) {
            System.out.println("电压不符!无法充电!");
        }
    }
}

test:

package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:46
 * @Des:
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("适配器模式");
        Phone phone = new Phone();
        phone.charging(new VoltageAdapter());
    }
}

Class Adapter Pattern Considerations and Details

1) Java is a single inheritance mechanism, so it is a disadvantage that the class adapter needs to inherit the src class, because it requires that dst must be an interface, which has certain limitations;

2) The methods of the src class will be exposed in the Adapter, which also increases the cost of use.

Since it inherits the src class, it can rewrite the methods of the src class according to the requirements, which enhances the flexibility of the Adapter.

2.2, object adapter mode

Continue to explain with the example of a charger in life. The charger itself is equivalent to an Adapter, and the 220V AC is equivalent to src (that is, the adapter). Our target dst (that is, the target) is 5V DC, which is completed using the object adapter mode.

package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:57
 * @Des:
 */
public class VoltageAdapter2Object implements IVoltage5V {
    private Voltage220V voltage220V;

    public VoltageAdapter2Object(Voltage220V voltage220V) {
        this.voltage220V = voltage220V;
    }

    @Override
    public int output5V() {
        int dstV = 0;
        if (voltage220V != null) {
            int srcV = voltage220V.output220V();
            dstV = srcV / 44;
        }
        return dstV;
    }
}
package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 14:46
 * @Des:
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("适配器模式");
        Phone phone = new Phone();
        //phone.charging(new VoltageAdapter());

        phone.charging(new VoltageAdapter2Object(new Voltage220V()));
    }
}

Object Adapter Pattern Considerations and Details

1) Object adapters and class adapters are actually the same idea, but they are implemented in different ways.

According to the principle of composition reuse, composition is used instead of inheritance, so it solves the limitation that class adapters must inherit src, and no longer requires that dst must be an interface.

2) Lower cost of use and more flexibility.

2.3, interface adapter mode

 Interface Adapter Pattern Introduction

Core idea: When you do not need to implement all the methods provided by the interface, you can first design an abstract class to implement the interface, and provide a default implementation (empty method) for each method in the interface, then the subclass of the abstract class can have a choice Override some methods of the parent class to achieve the requirements, which is suitable for the situation where an interface does not want to use all its methods.

package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 15:03
 * @Des:
 */
public interface InterfaceTest {
    void method1();
    void method2();
    void method3();
    void method4();
    void method5();
}
package com.cjian.gof;

/**
 * @Author: cjian
 * @Date: 2023/4/20 15:04
 * @Des:
 */
public class AbstractAdapter implements InterfaceTest {
    @Override
    public void method1() {
    }

    @Override
    public void method2() {
    }

    @Override
    public void method3() {
    }

    @Override
    public void method4() {
    }

    @Override
    public void method5() {
    }

    public static void main(String[] args) {
        new AbstractAdapter() {
            @Override
            public void method1() {
                // TODO Auto-generated method stub
                super.method1();
            }
        };
    }
}

Third, the application of the adapter mode in the framework

3.1 Application in SpringMVC framework

1) The  HandlerAdapter in SpringMvc  uses the adapter mode

2) Review of the process of SpringMVC processing requests:

DispatcherServlet calls HandlerMapping according to the request information, and parses the Handler corresponding to the request. After parsing to the corresponding Handler (that is, the Controller controller we usually say), it will be processed by the HandlerAdapter adapter. HandlerAdapter is the expected interface, the specific adapter implementation class is used to adapt the target class, and Controller is the class that needs to be adapted.

Why use the Adapter pattern in Spring MVC? There are many types of Controllers in Spring MVC, and different types of Controllers process requests in different ways. If the adapter mode is not used, DispatcherServlet directly obtains the corresponding type of Controller, and if else is needed to determine which subclass it is and then execute it.

3.2. Adapter mode in spring AOP

We know that the implementation of Spring AOP is based on the proxy mode, but the enhancement or advice (Advice) of Spring AOP uses the adapter mode, and the related interface is AdvisorAdapter. The commonly used types of Advice are: BeforeAdvice (before the target method is called, pre-advice), AfterAdvice (after the target method is called, post-notification), AfterReturningAdvice (after the target method is executed, before return) and so on. Each type of Advice (notification) has a corresponding interceptor: MethodBeforeAdviceInterceptor, AfterReturningAdviceAdapter, AfterReturningAdviceInterceptor. Spring's predefined notifications must be adapted to objects of the MethodInterceptor interface (method interceptor) type through the corresponding adapter (for example: MethodBeforeAdviceInterceptor is responsible for adapting MethodBeforeAdvice).

Guess you like

Origin blog.csdn.net/cj_eryue/article/details/130266365