您的位置:首页 > 其它

设计模式——适配器模式

2018-02-10 18:25 260 查看

设计模式——适配器模式

1-  适配器模式的定义

适配器模式的定义:将一个类的接口转换成客户需要的另外一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作,它结合了两个独立接口的功能。
No BB,Show Code!
 

2-  适配器模式具体实现代码

2-1定义需要适配的接口及实现

适配器模式的出现都是因为接口或者类与现在的实际系统不匹配造成的!
定义一个老接口,即需要适配的接口package designPattern.test.adapter.interf;

/**
* 老接口,需要适配的接口
*/
public interface OldInterface {
void oldMethod();
}
实现类package designPattern.test.adapter.impl;

import designPattern.test.adapter.interf.OldInterface;

/**
* 老接口的实现,被适配的类
*/
public class OldImpl implements OldInterface {

@Override
public void oldMethod() {
System.out.println("This is a OldInterface,old method!");
}

}

2-2定义新的接口及实现

定义一个现在系统使用的接口及实现package designPattern.test.adapter.interf;

/**
* 新接口
*/
public interface NewInterface{

void newMethod();

}实现类package designPattern.test.adapter.impl;

import designPattern.test.adapter.interf.NewInterface;

/**
* 新接口
*/
public class NewImpl implements NewInterface {

@Override
public void newMethod() {
System.out.println("This is a NewImpl newMethod");
}

}

2-3定义适配器

假设现在其他系统只能使用NewInterface的实现,这就需要使用适配器模式构造一个适配器对象。package designPattern.test.adapter;

import designPattern.test.adapter.impl.NewImpl;
import designPattern.test.adapter.interf.OldInterface;

/**
* 适配器,将需要适配的接口或类作为构造器参数传入
*/
public class OldNewAdapter extends NewImpl {

private OldInterface oldInterface;

public OldNewAdapter(OldInterface oldInterface) {
this.oldInterface = oldInterface;
}

@Override
public void newMethod() {
super.newMethod();
}

@Override
public void oldMethod() {
oldInterface.oldMethod();
}

}

3-  测试

测试代码如下package designPattern.test.adapter;

import designPattern.test.adapter.impl.OldImpl;
import org.junit.Test;

/**
* 测试类
*/
public class TestAdapter {

@Test
public void testAdapter(){
OldNewAdapter adapter = new OldNewAdapter(new OldImpl());
adapter.oldMethod();
adapter.newMethod();
}
}打印结果:This is a OldInterface,old method!
This is a NewImpl newMethod总结:适配器模式结合两个独立接口的功能!在使用时确定需要适配的类,适配的方法,这样就可以重用之前的接口和具体的实现!

4-  适配器模式典型应用

JDK中java.io包下的InputStreamReader就是适配器模式的典型应用,将一个InputStream对象作为传参传入InputStreamReader的构造器中,返回一个Reader的具体实现类,实现了从字节流到字符流的适配,具体代码如下:package designPattern.test.adapter.file;

import org.junit.Test;

import java.io.*;

/**
* InputStreamReader测试
*/
public class FileAdapterTest {

/**
* 适配器模式将一个InputStream接口适配成Reader接口
*/
@Test
public void testFileAdapter() throws Exception {
long start = System.currentTimeMillis();
Reader reader = new InputStreamReader(new FileInputStream(new File("D:/trace.log")));
printLog(reader);
System.out.println("============================Time:" + (System.currentTimeMillis() - start));
}

private void printLog(Reader reader) throws Exception {
int i = 0;
char[] chars = new char[1024];
while ((i = reader.read(chars)) != -1) {
String s = new String(chars);
System.out.println(s);
}
}
}对于文本文件,使用字符流可以获得更高的IO性能,但是在只有文本字节流的对象的情况下就可以使用InputStreamReader实现从InputStream到Reader的适配。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: