Adapter大概就是一个转换interface的class。就比如说现在我们有两个interface
public interface Student {
public void studentIntroduction();
}
public interface People {
public void peopleIntroduction();
}
一个是student,一个是people,然后随便建个人去implement student这个interface
public class Yidow implements Student {
public void studentIntroduction(){
System.out.println("I'm a student");
}
}
这时候我们就要想啦,学生也是人啊,为啥Yidow不能是个人呢?所以我们建一个adapter
public class Adapter implements People {
Student newStudent;
public adapter(Student std){
newStudent = std;
}
public void peopleIntroduction(){
newStudent.studentIntroduction();
}
}
建完adapter以后我们就可以这样用
public class Main {
public static void main(String[] args) {
Yidow yidow = new Yidow();
People adapterYidow = new Adapter(yidow);
yidow.studentIntroduction();
adapterYidow.peopleIntroduction();
}
}
Output:
I'm a student
I'm a student
所以其实output都是一样的,但是就是改变了一下interface