设计模式--适配器模式

first:推荐看Terry的设计模式的blog,真的很精彩,通俗易懂。

second: 首先拿出当时我老师教我设计模式时给的资料里面的一段话:

比较形象的,通俗讲解设计模式的一段话: “ 在朋友聚会上碰到了一个美女Sarah,从香港来的,可我不会说粤语,她不会说普通话,只好求助于我的朋友kent了,他作为我和Sarah之间的Adapter,让我和Sarah可以相互交谈了(也不知道他会不会耍我) 适配器(变压器)模式:把一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口原因不匹配而无法一起工作的两个类能够一起工作。适配类可以根据参数返还一个合适的实例给客户端。

 首先定义接口,抽象要设配的方法:

package com.soyoung.adapter;

public interface Show {

    public abstract String showBoy();
    
    
    public abstract String showGirl();
    
}
package com.soyoungboy.adapter;

public class Human{
    
    private String string;
    
    public Human(String string)
    {
        this.string=string;
    }
    
    
    public String showWithBoy(){
        return string+"is boy";
    }
    
    public String ShowWidthGirl(){
        return string+ "is girl";
    }
}
package com.soyoungboy.adapter;

public class Humanshow extends Human implements Show {
    
    public Humanshow(String string) {
        super(string);
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public String showBoy() {
        return showWithBoy();
    }
    
    @Override
    public String showGirl() {
        return ShowWidthGirl();
    }
    
    
    
}
package com.soyoungboy.adapter;

public class Main {
    
    public static void main(String[] args) {
        Human human = new Humanshow("lily ");
        String boy = human.showWithBoy();
        String girl =  human.ShowWidthGirl();
        System.out.println(boy);
        System.out.println(girl);
    }
    
}

结果为:

lily is boy
lily is girl

适配器模式分为两种模式

类适配器模式对象适配器模式

对象适配器模式:把被适配的类的api转换为目标类的api,与类的适配器模式不同,对象适配器模式不是使用继承链接到需要适配的类,而是使用代理关系连接到需要适配的类,直接将要适配的对象传递到adapter类里面,通过组合的形式实现接口兼容,而且也避免类适配器模式因为继承出现的奇怪的方法,更加灵活实用。android里面的adapter就是对象适配器模式。通过将传递进来的数据再getview里面进行处理,返回统一的view对象,会发生变化的部分比如数据独立交给用户处理,通过观察者模式解耦数据和UI,View和数据之间没有依赖,一个数据可应对多套布局。

 举个对象适配器的例子:

1 public class Source {
2 public void method1() {
3 System.out.println("this is original method!");
4 }
5 }
1 public interface Targetable {
2 /* 与原类中的方法相同 */
3 public void method1();
4 /* 新类的方法 */
5 public void method2();
6 }
public class Wrapper implements Targetable {
private Source source;
public Wrapper(Source source) {
super();
this.source = source;
}
@Override
public void method2() {
System.out.println("this is the targetable method!");
}
@Override
public void method1() {
source.method1();
}
}
--------------------------------------------------------------
public class AdapterTest {
public static void main(String[] args) {
Source source = new Source();
Targetable target = new Wrapper(source);
target.method1();
target.method2();
}
}
原文地址:https://www.cnblogs.com/androidsuperman/p/4437493.html