Writing in the front

  • Take notes on learning design patterns
  • Improve the flexible use of design patterns

Learning to address

www.bilibili.com/video/BV1G4…

www.bilibili.com/video/BV1Np…

Refer to the article

C.biancheng.net/view/1317.h…

Program source codeGitee.com/zhuang-kang…

10. Adapter pattern

10.1 Definition and features of the adapter pattern

An Adapter pattern is defined as follows: ** Converts the interface of one class into another interface that the customer expects, so that classes that would otherwise not work together due to interface incompatibations can work together. ** Adapter mode is divided into class structure mode and object structure mode, the former class coupling degree is higher than the latter.

The main advantages of this mode are as follows:

  • The client can transparently invoke the target interface through the adapter.
  • By reusing existing classes, programmers can reuse existing adapter classes without modifying the original code.
  • Decoupling the target class from the adapter class solves the problem of interface inconsistency between the target class and the adapter class.
  • It complies with the on/off principle in many business scenarios.

Its disadvantages are:

  • The adapter writing process needs to be considered in the context of business scenarios and can increase system complexity.
  • Increase code reading difficulty, reduce code readability, excessive use of adapters will make the system code messy.

10.2 Structure and implementation of adapter pattern

10.2.1 Structure of the adapter pattern

  1. Target interface: The interface expected by the current system service. It can be an abstract class or interface.
  2. Adaptee class: It is a component interface in an existing component library that is accessed and adapted.
  3. Adapter class: It is a converter that converts the Adapter interface into the target interface by inheriting or referencing the Adapter’s object, allowing customers to access the Adapter in the format of the target interface.

10.2.2 Code implementation

10.2.2.1 Class adapter mode

Voltage5V Target interface

package com.zhuang.adapter.classadapter;

/ * * *@Classname Voltage5V
 * @DescriptionDefine direct current *@Date 2021/3/21 14:14
 * @Created by dell
 */

public interface Voltage5V {
    // Define a standard charger to implement
    public int output5V(a);
}
Copy the code

Voltage220V

package com.zhuang.adapter.classadapter;

/ * * *@Classname Voltage220V
 * @DescriptionCreate ac *@Date 2021/3/21 14:13
 * @Created by dell
 */

public class Voltage220V {
    public int output220V(a) {
        System.out.println(Voltage output 220 VOLTS);
        return 220; }}Copy the code

VoltageAdapter

package com.zhuang.adapter.classadapter;

/ * * *@Classname VoltageAdapter
 * @DescriptionCreate a charger@Date 2021/3/21 14:14
 * @Created by dell
 */

public class VoltageAdapter extends Voltage220V implements Voltage5V {
    @Override
    public int output5V(a) {
        // Obtain ac 220V
        int output220V = output220V();
        / / to 5 v
        int output5V = output220V / 44;
        System.out.println("VoltageAdapter output 5 volts");
        returnoutput5V; }}Copy the code

Phone

package com.zhuang.adapter.classadapter;

/ * * *@Classname Phone
 * @DescriptionMobile phone class *@Date"2021/3/21 *@Created by dell
 */

public class Phone {
    public void charging(Voltage5V voltage5V) {
        if (voltage5V.output5V() == 5) {
            System.out.println("Five volts, rechargeable.");
        } else if (voltage5V.output5V() > 5) {
            System.out.println("The voltage is too high to charge."); }}}Copy the code

Client

package com.zhuang.adapter.classadapter;

/ * * *@Classname Client
 * @DescriptionClient class *@Date"2021/3/21 *@Created by dell
 */

public class Client {
    public static void main(String[] args) {
        System.out.println("== class adapter ==");
        Phone phone = new Phone();
        phone.charging(newVoltageAdapter()); }}Copy the code

Class adapter pattern considerations and details

  • Java is a single-inheritance mechanism, so the class adapter needs to inherit the Voltage5V class. This is a disadvantage, in addition to the requirement that the Target (Voltage5V) must be an interface, there are certain limitations;
  • Methods of the adapter Voltage220V class are exposed in the adapter VoltageAdapter class, which also increases the cost of use. But because it inherits the adapter Voltage220V class, it can override the methods of that class as required, making the VoltageAdapter class more flexible.

10.2.2.2 Object Adapter Mode

Voltage5V

package com.zhuang.adapter.objectadapter;

/ * * *@Classname Voltage5V
 * @DescriptionCharging 5 v *@Date2021/3/21 then *@Created by dell
 */

public interface Voltage5V {
    // Define a standard charger to implement
    public int output5V(a);
}
Copy the code

Voltage220V

package com.zhuang.adapter.objectadapter;

/ * * *@Classname Voltage220V
 * @DescriptionOutput 220V class *@Date2021/3/21 then *@Created by dell
 */

public class Voltage220V {
    public int output220V(a) {
        System.out.println(Voltage output 220 VOLTS);
        return 220; }}Copy the code

VoltageAdapter

package com.zhuang.adapter.objectadapter;

/ * * *@Classname VoltageAdapter
 * @DescriptionAdapter classes@DateBehold, 2021/3/21 *@Created by dell
 */

public class VoltageAdapter implements Voltage5V {

    private Voltage220V voltage220V;

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

    @Override
    public int output5V(a) {
        // Obtain ac 220V
        int output220V = voltage220V.output220V();
        / / to 5 v
        int output5V = output220V / 44;
        System.out.println("VoltageAdapter output 5 volts");
        returnoutput5V; }}Copy the code

Phone

package com.zhuang.adapter.objectadapter;

/ * * *@Classname Phone
 * @DescriptionMobile phone class *@DateBehold, 2021/3/21 *@Created by dell
 */

public class Phone {
    public void charging(Voltage5V voltage5V) {
        if (voltage5V.output5V() == 5) {
            System.out.println("Five volts, rechargeable.");
        } else if (voltage5V.output5V() > 5) {
            System.out.println("The voltage is too high to charge."); }}}Copy the code

Client

package com.zhuang.adapter.objectadapter;

/ * * *@Classname Client
 * @DescriptionObject adapter test class *@DateBehold, 2021/3/21 *@Created by dell
 */

public class Client {

    public static void main(String[] args) {
        System.out.println("== Object adapter ==);
        Phone phone = new Phone();
        phone.charging(new VoltageAdapter(newVoltage220V())); }}Copy the code

Object adapter pattern considerations and details

  • Object adapters and class adapters are essentially the same idea, but implemented differently.

  • According to the principle of composite reuse, the use of composition instead of inheritance, so it solves the class adapter VoltageAdapter must inherit Voltage220V limitations, also no longer mandatory Voltage5V must be an interface. Cheaper to use and more flexible. Therefore, the object adapter pattern is one of the commonly used adapter patterns.

10.2.2.3 Interface Adapter Mode

Animation

package com.zhuang.adapter.interfaceadapter;

/ * * *@Classname Animation
 * @DescriptionAnimation interface@Date2021/3/21 whoever eats *@Created by dell
 */

public interface Animation {
    public void method1(a);

    public void method2(a);

    public void method3(a);

    public void method4(a);

    public void method5(a);
}
Copy the code

AnimationAdapter

package com.zhuang.adapter.interfaceadapter;

/ * * *@Classname AnimationAdapter
 * @DescriptionInterface adapter class *@Date 2021/3/21 14:48
 * @Created by dell
 */

public class AnimationAdapter implements Animation {
    // All empty implementations
    @Override
    public void method1(a) {}@Override
    public void method2(a) {}@Override
    public void method3(a) {}@Override
    public void method4(a) {}@Override
    public void method5(a) {}}Copy the code

JFrameAnimation

package com.zhuang.adapter.interfaceadapter;

/ * * *@Classname JFrameAnimation
 * @DescriptionAdapter subclass *@Date2021/3/21 were *@Created by dell
 */

public class JFrameAnimation extends AnimationAdapter {
    @Override
    public void method1(a) {
        System.out.println("Method1 () is called...");
    }

    @Override
    public void method2(a) {
        System.out.println("Method2 () is called..."); }}Copy the code

Client

package com.zhuang.adapter.interfaceadapter;

/ * * *@Classname Client
 * @DescriptionClient class *@Date2021/3/21 name *@Created by dell
 */

public class Client {
    public static void main(String[] args) {
        JFrameAnimation animation = newJFrameAnimation(); animation.method1(); animation.method2(); }}Copy the code

10.3 SpringMVC source code Parsing

Controller

package com.zhuang.adapter.springmvc;

/ * * *@Classname Controller
 * @DescriptionSpringmvc Controller source code *@Date 2021/3/21 14:53
 * @Created by dell
 */

// Multiple Controller implementations
public interface Controller {}class HttpController implements Controller {
    public void doHttpHandler(a) {
        System.out.println("http..."); }}class SimpleController implements Controller {
    public void doSimplerHandler(a) {
        System.out.println("simple..."); }}class AnnotationController implements Controller {
    public void doAnnotationHandler(a) {
        System.out.println("annotation..."); }}Copy the code

DispatchServlet

package com.zhuang.adapter.springmvc;

import java.util.ArrayList;
import java.util.List;

/ * * *@Classname DispatchServlet
 * @DescriptionSpringmvc DispatchServlet source *@Date2021/3/21 any valiant man *@Created by dell
 */

public class DispatchServlet {
    public static List<HandlerAdapter> handlerAdapters = new ArrayList<HandlerAdapter>();

    public DispatchServlet(a) {
        handlerAdapters.add(new AnnotationHandlerAdapter());
        handlerAdapters.add(new HttpHandlerAdapter());
        handlerAdapters.add(new SimpleHandlerAdapter());
    }

    public void doDispatch(a) {

        // SpringMVC fetches the handler object from request,
        // The adapter can get the desired Controller
        HttpController controller = new HttpController();
        // AnnotationController controller = new AnnotationController();
        //SimpleController controller = new SimpleController();
        // Get the corresponding adapter
        HandlerAdapter adapter = getHandler(controller);
        // Execute the corresponding controller corresponding method through the adapter
        adapter.handle(controller);

    }

    public HandlerAdapter getHandler(Controller controller) {
        // Traversal: returns the corresponding adapter based on the obtained controller(handler)
        for (HandlerAdapter adapter : this.handlerAdapters) {
            if (adapter.supports(controller)) {
                returnadapter; }}return null;
    }

    public static void main(String[] args) {
        new DispatchServlet().doDispatch(); // http...}}Copy the code

HandlerAdapter

package com.zhuang.adapter.springmvc;

/ * * *@Classname HandlerAdapter
 * @DescriptionSpringmvc HandlerAdapter source code *@Date 2021/3/21 14:53
 * @Created by dell
 */

// define an Adapter interface
public interface HandlerAdapter {
    public boolean supports(Object handler);

    public void handle(Object handler);
}

// Multiple adapter classes

class SimpleHandlerAdapter implements HandlerAdapter {

    @Override
    public void handle(Object handler) {
        ((SimpleController) handler).doSimplerHandler();
    }

    @Override
    public boolean supports(Object handler) {
        return (handler instanceofSimpleController); }}class HttpHandlerAdapter implements HandlerAdapter {

    @Override
    public void handle(Object handler) {
        ((HttpController) handler).doHttpHandler();
    }

    @Override
    public boolean supports(Object handler) {
        return (handler instanceofHttpController); }}class AnnotationHandlerAdapter implements HandlerAdapter {

    @Override
    public void handle(Object handler) {
        ((AnnotationController) handler).doAnnotationHandler();
    }

    @Override
    public boolean supports(Object handler) {

        return (handler instanceofAnnotationController); }}Copy the code

Write in the last

  • If my article is useful to you, please give me a click 👍, thank you 😊!
  • If you have any questions, please point them out in the comments section! 💪