适配器模式(9)
来源:互联网 发布:关于淘宝诈骗的视频 编辑:程序博客网 时间:2024/06/07 22:02
适配器模式定义:将一个类的接口转换成另一种接口,让原本接口不兼容的类可以兼容。
现实中的例子:电源适配器(充电器)。由于设备的不同,输入电流电压有不同的标准,但是我国的家用电压是220V标准,所以需要经过电源适配器对电流电压进行转换才能安全充电。
适配器模式有两种形式:
对象适配器:适配器实现(implement)目标接口,且适配器类中有被适配对象的引用
类适配器: 适配器实现(implement)目标接口,适配器类直接继承被适配对象的类
适配器适配过程:从用户的角度看不到被适配者,是解耦的。
用户调用适配器转化出来的目标接口
适配器再调用被适配者的相关接口方法
用户收到反馈结果,感觉只是和目标接口交互
类图:对象适配器
代码示例:
1
2
3
4
5
6
7
8
//标准家用插座
public
class
NormalSocket {
private
final
int
v =
220
;
public
int
out(){
return
v;
}
}
1
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
//小米手机
public
class
MIMobile {
private
final
String name =
"小米手机"
;
private
byte
power;
public
synchronized
void
charge(USBSocket electrictIn){
if
(electrictIn==
null
) {
return
;
}
if
(electrictIn.out()==
5
){
new
Thread(){
@Override
public
void
run() {
while
(power <
100
){
power++;
System.out.println(
"正在充电中,当前电量-------: "
+power);
try
{
Thread.sleep(
1000
);
}
catch
(InterruptedException e) {
System.out.println(
"充电器烧了,断开电源"
);
return
;
}
}
System.out.println(
"充电完成"
);
}
}.start();;
}
else
{
System.out.println(
"充电保护,断开充电源"
);
}
}
}
1
2
3
4
5
//USB充电器
public
interface
USBSocket {
public
int
out();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//小米电源适配器
public
class
MIUSBSocketAdater
implements
USBSocket {
private
NormalSocket normalSocket;
public
MIUSBSocketAdater(NormalSocket normalSocket) {
this
.normalSocket = normalSocket;
}
@Override
public
int
out() {
if
(normalSocket!=
null
){
return
5
;
}
else
{
System.out.println(
"无电源输入"
);
return
0
;
}
}
}
1
2
3
4
5
6
7
8
public
class
Main {
public
static
void
main(String[] args) {
MIMobile mobile =
new
MIMobile();
NormalSocket normalSocket =
new
NormalSocket();
MIUSBSocketAdater miusbSocketAdater =
new
MIUSBSocketAdater(normalSocket);
mobile.charge(miusbSocketAdater);
}
}
0 0
- 适配器模式(9)
- 适配器模式(Adapter)
- 适配器模式(Adapter)
- 适配器(Adapter)模式
- ADAPTER(适配器)模式
- 适配器模式(adapter)
- 适配器模式(Adapter)
- Adapter(适配器)模式
- 适配器模式(Adapter)
- 适配器模式(Java)
- 适配器模式(Adaptor)
- 适配器(Adapter)模式
- Adapter(适配器模式)
- 适配器模式(adapter)
- 适配器(Adapter)模式
- 适配器模式(Adapter)
- 适配器模式(Adapter)
- 适配器(Adapter)模式
- 9个offer,12家公司,35场面试,从微软到谷歌,应届计算机毕业生的2012求职之路
- 加了FLAG_ACTIVITY_SINGLE_TOP后,不能再多次创建MainActivity
- 考察团组成
- Emacs学习笔记(1)——安装及默认路径修改
- android通过jni调用C代码socket出错问题
- 适配器模式(9)
- RFC学习笔记 -- 5245 ICE & 3261 SIP
- linux查看文件系统的使用空间和文件夹占用空间的命令
- Java内部类详解
- android应用性能测试——cpu的占用率
- Android图片加载
- Source Insight:Symbol not found
- 使用.net 3.5的DataContractJsonSerializer进行JSON Serialization
- shell脚本