Skip to content

Commit eeffcba

Browse files
committed
9.3完全解耦
适配器模式练习题
1 parent e59b46d commit eeffcba

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

bin/unit9/StringAdapter.class

807 Bytes
Binary file not shown.
1.46 KB
Binary file not shown.
Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
package unit9;
2+
3+
import unit9.pack3.Processor;
4+
import unit9.pack3.Apply;;
5+
6+
/**
7+
* 创建一个类,它有一个方法用于接受一个String类型的参数,生成的结果是该参数中每一对字符进行互换。
8+
* 对该类进行适配,使它可以用于interfaceprocessor.Apply.process()。
9+
*
10+
* 适配器模式的使用
11+
*
12+
* @author Administrator
13+
*
14+
*/
15+
public class _9_11_AdapterInterface {
16+
public String name() {
17+
return getClass().getSimpleName();
18+
}
19+
20+
public String change(String str) {
21+
char[] chars = str.toCharArray();
22+
23+
int length = chars.length - 1;
24+
for (int i = 0; i < length / 2; i++) {
25+
char a = chars[i];
26+
chars[i] = chars[length - i];
27+
chars[length - i] = a;
28+
}
29+
30+
StringBuilder builder = new StringBuilder();
31+
for (char c : chars) {
32+
builder.append(c);
33+
}
34+
return builder.toString();
35+
}
36+
37+
public static void main(String[] args) {
38+
String str = "change this sentences.";
39+
Apply.process(new StringAdapter(new _9_11_AdapterInterface()), str);
40+
}
41+
}
42+
43+
// 首先创建适配器,适配器中的代码将接受你所拥有的接口,并产生你所需要的接口
44+
class StringAdapter implements Processor {
45+
_9_11_AdapterInterface ai;
46+
47+
public StringAdapter(_9_11_AdapterInterface ai) {
48+
this.ai = ai;
49+
}
50+
51+
@Override
52+
public String name() {
53+
return ai.name();
54+
}
55+
56+
@Override
57+
public Object process(Object input) {
58+
return ai.change((String) input);
59+
}
60+
}
61+
62+
/*
63+
Output:
64+
Using Processor _9_11_AdapterInterface
65+
.secnetness iht egnahc
66+
67+
bug:
68+
Apply没有正确导包,使用了一个错误的地方的Apply,这个Apply的参数和这个程序要使用的不一致
69+
*/

0 commit comments

Comments
 (0)