一、适配器模式:
适配器模式适用于将不同接口之间进行沟通,例如电脑与手机进行数据传输需要USB进行辅助,而USB就称为适配器,沟通手机与电脑的适配装置。
二、分类:
1、类适配器模式:
类适配器模式是基于面向对象思想,把执行目标视为接口,被适配者依赖适配器实现目标接口功能,二适配器即适配者则是整合两者功能,实现把两个不想关的类或接口实现一个预期的功能。
案例:适配Properties类
适配目标
public interface FileIO {
void readFromFile(String fileName) throws IOException;
void writeToFile(String fileName) throws IOException;
void setValue(String key,String value);
String getValue(String key);
}
适配器
public class FileProperties extends Properties implements FileIO{
private Properties properties;
public FileProperties(){
properties = new Properties();
}
@Override
public void readFromFile(String fileName) throws IOException {
InputStream inputStream = new FileInputStream(fileName);
properties.load(inputStream);
inputStream.close();
}
@Override
public void writeToFile(String fileName) throws IOException {
Set<String> set = properties.stringPropertyNames();
File file = new File(fileName);
boolean success = true;
if(!file.exists()){
success = file.createNewFile();
}
if(success){
OutputStream outputStream = new FileOutputStream(file);
for (String key : set) {
properties.store(outputStream,properties.getProperty(key));
}
outputStream.flush();
outputStream.close();
}else {
throw new CommonException("文件创建失败");
}
}
@Override
public void setValue(String key, String value) {
properties.setProperty(key,value);
}
@Override
public String getValue(String key) {
return properties.getProperty(key);
}
}
被适配者:
public class Properties extends Hashtable<Object,Object>
测试类:
public class TestApp {
public static void main(String[] args) {
FileIO fileIO = new FileProperties();
String fileName = "J:\\secondj\\hello.txt";
String outPutFileName = "J:\\secondj\\hellos.txt";
try {
fileIO.readFromFile(fileName);
fileIO.setValue("name","test");
fileIO.setValue("hobby","paint");
System.out.println(fileIO.getValue("year"));
System.out.println(fileIO.getValue("name"));
System.out.println(fileIO.getValue("hobby"));
fileIO.writeToFile(outPutFileName);
}catch (Exception e){
e.printStackTrace();
}
}
}
2、对象适配器模式:
对象适配器的应用更像是redisTemplate的工具类封装,用了适配对象实现了原对象的功能,相比于类适配器,类适配器具有抽象的接口,可以屏蔽实现类的具体流程,可以根据适配器的不同而动态选择执行对象,有更好的灵活性。