Java Description Design Patterns (07): Adapter Patterns

Posted by gplevritis on Sun, 15 Sep 2019 16:13:36 +0200

This article source code: GitHub. Click here || GitEE. Click here

Introduction of adapter mode

1. Basic concepts

The adapter pattern transforms the interface of one class into another that the client expects, so that two classes that could not work together because of interface mismatch can work together. There are three types of adapter modes: class adapter mode and object adapter mode, and default (interface) adapter.

2. Life Scene

Based on the adapter mode, the 220 V voltage is converted to the required 110 V voltage.

public class C01_InScene {
    public static void main(String[] args) {
        CurrentAdapter adapter = new CurrentAdapter() ;
        System.out.println(adapter.get110VCurrent()) ;
    }
}
// 220V current
class Current220V {
    public int get220VCurrent (){
        return 220 ;
    }
}
// 110V Current Interface
interface Current110V {
    int get110VCurrent () ;
}
// Current adapter
class CurrentAdapter extends Current220V implements Current110V {
    // Current Conversion Method
    @Override
    public int get110VCurrent() {
        int high = get220VCurrent() ;
        int low = high/2 ;
        return low ;
    }
}

II. Class adapter

1. Brief Introduction of Model

The class adapter pattern converts the API of the adapted class into the API of the target class.

2. Core role

  • Target role

This is the expected interface.

  • Source (Adapee) role:

Now you need an adapted interface.

  • Adaper role

The adapter class is the core of this pattern. The adapter converts the source interface to the target interface.

3. Source Code Implementation

interface Target {
    void sampleOperation1();
    void sampleOperation2();
}
class Adaptee {
    public void sampleOperation1(){
        System.out.println("Adaptee.sampleOperation1()");
    }
}
class Adapter extends Adaptee implements Target{

    @Override
    public void sampleOperation2() {
        System.out.println("Adapter.sampleOperation2()");
    }
}

3. Object adapter

1. Brief Introduction of Model

Like the class adapter pattern, the object adapter pattern converts the API of the adapted class into the API of the target class. Unlike the class adapter pattern, the object adapter pattern connects to the Adaptee class not by inheritance, but by delegation.

2. Source Code Implementation

interface Target1 {
    void sampleOperation1();
    void sampleOperation2();
}
class Adaptee1 {
    public void sampleOperation1(){
        System.out.println("Adaptee.sampleOperation1()");
    }
}
class Adapter1 implements Target1 {
    private Adaptee1 adaptee ;
    public Adapter1 (Adaptee1 adaptee){
        this.adaptee = adaptee;
    }

    public void sampleOperation1() {
        this.adaptee.sampleOperation1();
    }

    @Override
    public void sampleOperation2() {
        System.out.println("Adapter.sampleOperation2()");
    }
}

IV. Interface adapter

1. Brief Introduction of Model

The Default Adapter pattern provides a default implementation for an interface so that subtypes can be extended from this default implementation rather than from the original interface.

2. Source Code Implementation

public class C04_AdapterInte {
    public static void main(String[] args) {
        ServiceAdapter adapter = new ServiceAdapter(){
            @Override
            public int serviceOperation2() {
                return 22 ;
            }
        };
        System.out.println(adapter.serviceOperation2());
    }
}
interface AbstractService {
    void serviceOperation1();
    int serviceOperation2();
    String serviceOperation3();
}
class ServiceAdapter implements AbstractService{
    @Override
    public void serviceOperation1() {

    }
    @Override
    public int serviceOperation2() {
        return 0;
    }
    @Override
    public String serviceOperation3() {
        return null;
    }
}

5. Spring Framework Application

1. Application Scenario Description

When Spring Mvc executes control execution requests, there is such a process

1) The front controller Dispatcher Servlet calls the processor adapter to execute the Handler (that is, Controller).
2) The processor adapter executes the Handler and returns the ModelAndView to the adapter;
3) The processor adapter returns ModelAndView to the front-end controller;

2. Process analysis

  • Core interface and Implementation

Controller and Handler Adapter are two core interfaces.

  • HandlerAdapter

The adapter interface enables the Handler to have the corresponding adapter implementation class, and the adapter performs the corresponding method instead of the Handler (control layer Controller).

public interface HandlerAdapter {
    // Determine whether the type matches
    boolean supports(Object var1);
    // Execution method, return ModelAndView
    ModelAndView handle(HttpServletRequest var1, 
                        HttpServletResponse var2, Object var3) 
                        throws Exception;
}

The support () method is passed into the processor to determine whether the adapter supports it or not, and if so returns the supported adapter implementation class.

  • DispatchServlert

Extraction of source code embodies several steps of the process.

protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HandlerExecutionChain mappedHandler = null;
    mappedHandler = this.getHandler(processedRequest);
    HandlerAdapter ha = this.getHandlerAdapter(mappedHandler.getHandler());
    mv = ha.handle(processedRequest, response, mappedHandler.getHandler());
    mappedHandler.applyPostHandle(processedRequest, response, mv);
}
  • SimpleControllerHandlerAdapter

Finally, we look at the implementation of support and handle.

public class SimpleControllerHandlerAdapter implements HandlerAdapter {
    public SimpleControllerHandlerAdapter() {
    }
    public boolean supports(Object handler) {
        return handler instanceof Controller;
    }
    public ModelAndView handle(HttpServletRequest request, 
                               HttpServletResponse response, Object handler) 
                               throws Exception {
        return ((Controller)handler).handleRequest(request, response);
    }
}

6. Advantages and disadvantages of adapters

1. Advantage analysis

For better reusability, the system needs to use existing classes, and such interfaces do not meet the needs of the system. Then these functions can be better reused through the adapter mode. Better scalability.

2. Disadvantage analysis

Too many adapters will make the system very messy and difficult to control as a whole.

7. Source code address

GitHub·address
https://github.com/cicadasmile/model-arithmetic-parent
GitEE·address
https://gitee.com/cicadasmile/model-arithmetic-parent

Topics: Java github Spring