
Java设计模式-适配器模式test
2023-03-28 / highPhone啊
定义
适配器模式的定义如下:
适配器模式: 将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。
结构
目标抽象类(Target)
目标抽象类定义了客户需要的接口,可以是一个抽象类,也可以是一个接口,也可以是一个具体类。但在类适配器的实现中,他只能是接口
适配者类(Adaptee)
适配者类,是被适配的角色,它定义了一个已经存在的接口,这个接口目标抽象类不兼容,需要适配。适配者类一般是一个具体类,包含了客户希望使用的业务方法。
适配器类(Adapter)
适配器模式的核心,作为一个转换器,是不兼容的Target和Adaptee可以进行适配。
实现
适配器模式有类适配器和对象适配器两种实现
类适配器
在类适配器中,Adapter通过实现Target接口并继承Adaptee来实现适配兼容,其结构图如下:
对象适配器
在对象适配器中,Adapter通过继承Target并关联一个Adaptee来实现适配兼容,其结构图如下:
后记
在JDK源码中,有一些代码是对适配器模式的经典应用:
java.util.Arrays#asList()1
2
3public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}java.util.Collections#list()1
2
3
4
5
6public static <T> ArrayList<T> list(Enumeration<T> e) {
ArrayList<T> l = new ArrayList<>();
while (e.hasMoreElements())
l.add(e.nextElement());
return l;
}java.util.Collections#enumeration()1
2
3
4
5
6
7
8
9
10
11
12
13public static <T> Enumeration<T> enumeration(final Collection<T> c) {
return new Enumeration<T>() {
private final Iterator<T> i = c.iterator();
public boolean hasMoreElements() {
return i.hasNext();
}
public T nextElement() {
return i.next();
}
};
}java.io.InputStreamReader(InputStream)传入InputStream返回一个Reader1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20public class InputStreamReader extends Reader {
//解码器,InputStreamReader.read()实际是调用sd.read()来工作。
private final StreamDecoder sd;
/**
* Creates an InputStreamReader that uses the default charset.
*
* @param in An InputStream
*/
public InputStreamReader(InputStream in) {
super(in);
try {
sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
} catch (UnsupportedEncodingException e) {
// The default encoding should always be available
throw new Error(e);
}
}
}java.io.OutputStreamWriter(OutputStream)传入OutputStream返回一个Writer1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40public class OutputStreamWriter extends Writer {
//编码器,OutputStreamWriter.write()实际是调用se.write()来工作。
private final StreamEncoder se;
/**
* Creates an OutputStreamWriter that uses the named charset.
*
* @param out
* An OutputStream
*
* @param charsetName
* The name of a supported
* {@link java.nio.charset.Charset charset}
*
* @exception UnsupportedEncodingException
* If the named encoding is not supported
*/
public OutputStreamWriter(OutputStream out, String charsetName)
throws UnsupportedEncodingException
{
super(out);
if (charsetName == null)
throw new NullPointerException("charsetName");
se = StreamEncoder.forOutputStreamWriter(out, this, charsetName);
}
/**
* Creates an OutputStreamWriter that uses the default character encoding.
*
* @param out An OutputStream
*/
public OutputStreamWriter(OutputStream out) {
super(out);
try {
se = StreamEncoder.forOutputStreamWriter(out, this, (String)null);
} catch (UnsupportedEncodingException e) {
throw new Error(e);
}
}
}
本文链接:https://highphone.xyz/d350718f.html