Java适配器模式是为了解决合作开发中,当接口方法与实现方法不太匹配时(譬如方法名字不相同),提供的中间件来匹配接口与实现。
接口IStudy中提供了一个write方法,但是在StudyImpl类中有和write相同的功能的一个方法,但是名字是xie,所以我们需要一个适配器来将两者关联起来
package com.vincent.designpatterns.adapter;
/**
* Created by vincent on 14-10-21.
*/
public interface IStudy {
void write();
}
package com.vincent.designpatterns.adapter;
/**
* Created by vincent on 14-10-21.
*/
public class StudyImpl {
public void xie(){
System.out.println("学习写字");
}
}
package com.vincent.designpatterns.adapter;
/**
* Created by vincent on 14-10-21.
*/
public class StudyAdapter extends StudyImpl implements IStudy{
@Override
public void write() {
this.xie();
}
}
package com.vincent.designpatterns.adapter;
/**
* Created by vincent on 14-10-21.
*/
public class Main {
public static void main(String[] args) {
IStudy study=new StudyAdapter();
study.write();
}
}
最后输出结果是:学习写字
通过适配器,接口和方法关联起来了