spring 与设计模式(行为型)之Adapter模式

一、前言

将两个不兼容的类整合在一起使用,属于结构模式,需要有Adaptee和Adapter两个身份。生活中我有许多场景是使用到Adapter模式,例如:苹果充电器,android充电器,现在需要一个可以万能充,下面以这个需求有例子。

二、UML

Adapter说白了,其实是组合和继承的混合使用,其他在我们写的代码中使用过许多次,只是我们没有意识到这其他是一个Adapter,包括我们写的许多springMVC,定义的Service

spring 与设计模式(行为型)之Adapter模式_第1张图片


如图:如果两个类之间像AndroidPower和ApplePower有共性的接口或者方法,我们在类Adapter往往注入接口就可以

如果两个是比较不相关或者方法名也不相同,Adapter往往需要继承一个类然后注入一个类,继承的那个类如SquarePeg作为目标(target),RoundPeg作为被适配者Adaptee

PegAdapter作为适配器(Adaper),最终的目的是使PegAdapter既能打方桩又能打圆桩。

package com.bitch.design.action.adapter;

/**
 * Adaptee
 * @author chenhaipeng
 * @version 1.0
 * @date 2015/11/01 22:16
 */
public class RoundPeg {
    public void insertIntohole(String msg){
        System.out.println("RoundPeg insertIntoHole:"+msg);
    }
}

package com.bitch.design.action.adapter;

/**
 * 方形桩 Target
 * @author chenhaipeng
 * @version 1.0
 * @date 2015/11/01 22:11
 */
public class SquarePeg {
    public void insert(String str){
        System.out.println("SquarePeg insert():"+str);
    }
}

package com.bitch.design.action.adapter;

/**
 * Adapter
 * @author chenhaipeng
 * @version 1.0
 * @date 2015/11/01 22:58
 */
public class PegAdapter extends SquarePeg {
    private RoundPeg roundPeg;

    public PegAdapter(RoundPeg roundPeg) {
        this.roundPeg = roundPeg;
    }

    public void insertIntohole(String str){
        roundPeg.insertIntohole(str);
    }

    public PegAdapter() {
    }
}

测试代码如下:

package com.bitch.design.action.adapter;

import org.junit.Test;

/**
 * @author chenhaipeng
 * @version 1.0
 * @date 2015/11/01 23:16
 */
public class MainTest {
    @Test
    public void testAdapter(){
        RoundPeg roundPeg = new RoundPeg();
        PegAdapter adapter = new PegAdapter(roundPeg);
        adapter.insertIntohole("RoundPeg...........");

        PegAdapter adapter2 = new PegAdapter();
        adapter2.insert("SquarePeg...............");

    }
}

三、Adapter在spring 中使用

将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。 
spring中在对于aop的处理中有Adapter模式的例子,见如下图: 
spring 与设计模式(行为型)之Adapter模式_第2张图片 
由于Advisor链需要的是MethodInterceptor对象,所以每一个Advisor中的Advice都要适配成对应的MethodInterceptor对象。

 






你可能感兴趣的:(spring与设计模式)