어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

이 문서 자료 : GitHub의이 · 여기를 클릭 || GitEE · 여기를 클릭하십시오

I. 서론 어댑터 모드

1, 기본 개념

두 클래스가 가진 것을 함께 작동하지 않을 수있는 인터페이스 불일치에 의해 함께 작업 할 수 있도록 클라이언트 인터페이스에 대한 클래스의 어댑터 모드 인터페이스는 다른 기대합니다. 어댑터 모드 어댑터 모드와 클래스 객체 어댑터 모드, 기본 (인터페이스) 세 가지 다른 형태의 어댑터가.

인생의 2, 장면

기반 어댑터 ​​모드, 220V의 전압은 110V가 필요로하는 전압으로 변환된다.

public class C01_InScene {
    public static void main(String[] args) {
        CurrentAdapter adapter = new CurrentAdapter() ;
        System.out.println(adapter.get110VCurrent()) ;
    }
}
// 220V电流
class Current220V {
    public int get220VCurrent (){
        return 220 ;
    }
}
// 110V电流接口
interface Current110V {
    int get110VCurrent () ;
}
// 电流适配器
class CurrentAdapter extends Current220V implements Current110V {
    // 电流转换方法
    @Override
    public int get110VCurrent() {
        int high = get220VCurrent() ;
        int low = high/2 ;
        return low ;
    }
}

둘째, 어댑터 클래스

1, 모델 설명

대상 클래스의 클래스의 클래스에 적응 어댑터 모드는 API의 API로 변환.
어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

2, 핵심 역할

  • 대상 (대상)의 역할

이 모양을 얻을 수있는 인터페이스입니다.

  • 소스 (Adapee) 역할 :

이제 우리는 인터페이스를 적용해야합니다.

  • 어댑터 (Adaper) 역할

이 클래스의 어댑터는 핵심 모드입니다. 소스 인터페이스 어댑터는 대상 인터페이스를 변환합니다.

3, 소스 코드 구현

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()");
    }
}

셋째, 개체 어댑터

1, 모델 설명

어댑터 모드와 클래스의 변환 등, 어댑터 API 스키마 객체와 마찬가지로 대상 클래스의 API가 될하도록하고, 어댑터 패턴 클래스는 다른, 어댑터 패턴 객체는 상속을 사용 그 Adaptee 클래스에 연결된 것이 아니라, 위임 된 연결 클래스에 그 Adaptee 관계.

어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

2, 소스 코드 구현

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()");
    }
}

넷째, 인터페이스 어댑터

1, 모델 설명

기본 (인터페이스) 어댑터 (기본 어댑터) 모드 인터페이스 아형이 원래의 인터페이스로부터 확장 할 필요없이,이 기본으로부터 연장하도록 구현 될 수 있고, 기본 구현을 제공한다.

어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

도 2에서, 소스 코드를 달성

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;
    }
}

다섯, 스프링 프레임 워크 응용 프로그램

1, 응용 프로그램 현장 설명

되면 실행 제어 SpringMvc 실행 요구, 이러한 공정

1)의 DispatcherServlet 처리기 (즉, 컨트롤러) 호출 프로세서 컨트롤러 어댑터를 행한다 항,
2) 어댑터 프로세서 핸들러를 수행 할 ModelAndView를 어댑터에 리턴]
. 3) 선단 처리부 어댑터는의 ModelAndView 컨트롤러 반환

2 프로세스 분석

  • 코어 인터페이스 및 구현

컨트롤러 및 HandlerAdapter 개의 코어 인터페이스.
어댑터 모드 : (07)에 설명 된 자바 디자인 패턴
어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

  • 핸들러 어댑터

해당 어댑터 구현 클래스 처리기 대신 어댑터 처리기 (제어 계층 제어기) 각각의 방법이 수행되는 원인 아답터 인터페이스.

public interface HandlerAdapter {
    // 判断类型是否匹配
    boolean supports(Object var1);
    // 执行方法,返回ModelAndView
    ModelAndView handle(HttpServletRequest var1, 
                        HttpServletResponse var2, Object var3) 
                        throws Exception;
}

프로세서 전달 지지체 () 메소드를 구현 클래스가 반환되는 경우, 어댑터 지원 지원 어댑터를 지원할지 여부를 결정한다.

  • DispatchServlert

여러 단계로 구현 소스 추출 과정.

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

마지막으로, 특정 구현을보고 두 가지 방법으로 처리를 지원합니다.

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);
    }
}

여섯째, 장점과 단점 어댑터

1 장점 분석

더 나은 재사용, 시스템은 기존 클래스의 사용을 필요로하며, 이러한 인터페이스는 시스템의 요구 사항을 충족하지 않습니다. 그런 다음 어댑터 모드를 통해 더 나은 재사용을 얻기 위해 이러한 기능을 활성화합니다. 더 나은 확장 성을 제공합니다.

2 결점 분석

과도한는 전체를 제어 할 시스템이 매우 혼란하고 어려운 만들기 위해 어댑터를 사용합니다.

세븐, 소스 주소

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

어댑터 모드 : (07)에 설명 된 자바 디자인 패턴

추천

출처blog.51cto.com/14439672/2438061