java适配器模式的两种分类

1、类适配器模式

实现方式:定义一个适配器类来实现当前系统的业务接口,同时又继承现有组件库中已经存在的组件。

publicclassHelloWorld{
publicstaticvoidmain(String[]args){
Computercomputer=newComputer();
SDCardsdCard=newSDCardImpl();
System.out.println(computer.readSD(sdCard));

System.out.println("------------");

SDAdapterTFadapter=newSDAdapterTF();
System.out.println(computer.readSD(adapter));
}
}

//SD卡的接口
interfaceSDCard{
//读取SD卡功能
StringreadSD();

//写入SD卡功能
voidwriteSD(Stringmsg);
}

//SD卡实现类
classSDCardImplimplementsSDCard{
@Override
publicStringreadSD(){
Stringmsg="sdcardreadamsg:hellosdcard";
returnmsg;
}

@Override
publicvoidwriteSD(Stringmsg){
System.out.println("sdcardwritemsg:"+msg);
}
}

//电脑类
classComputer{
publicStringreadSD(SDCardsdCard){
if(sdCard==null){
thrownewNullPointerException("sdcardnull");
}
returnsdCard.readSD();
}
}

//TF卡接口
interfaceTFCard{
//读取TF卡功能
StringreadTF();

//写入TF卡功能
voidwriteTF(Stringmsg);
}

//TF卡实现类
classTFCardImplimplementsTFCard{
@Override
publicStringreadTF(){
Stringmsg="sdcardreadamsg:hellotfcard";
returnmsg;
}

@Override
publicvoidwriteTF(Stringmsg){
System.out.println("tfcardwritemsg:"+msg);
}
}

//定义适配器类(SD兼容TF)
classSDAdapterTFextendsTFCardImplimplementsSDCard{
@Override
publicStringreadSD(){
System.out.println("adapterreadtfcard");
returnreadTF();
}

@Override
publicvoidwriteSD(Stringmsg){
System.out.println("adapterwritetfcard");
writeTF(msg);
}
}

2、对象适配器模式

实现方式:对象适配器模式可采用将现有组件库中已经实现的组件引入适配器中,该类同时实现当前系统的业务接口。

publicclassHelloWorld{
publicstaticvoidmain(String[]args){
Computercomputer=newComputer();
SDCardsdCard=newSDCardImpl();
System.out.println(computer.readSD(sdCard));

System.out.println("------------");

TFCardtfCard=newTFCardImpl();
SDAdapterTFadapter=newSDAdapterTF(tfCard);
System.out.println(computer.readSD(adapter));
}
}

//SD卡的接口
interfaceSDCard{
//读取SD卡功能
StringreadSD();

//写入SD卡功能
voidwriteSD(Stringmsg);
}

//SD卡实现类
classSDCardImplimplementsSDCard{
@Override
publicStringreadSD(){
Stringmsg="sdcardreadamsg:hellosdcard";
returnmsg;
}

@Override
publicvoidwriteSD(Stringmsg){
System.out.println("sdcardwritemsg:"+msg);
}
}

//电脑类
classComputer{
publicStringreadSD(SDCardsdCard){
if(sdCard==null){
thrownewNullPointerException("sdcardnull");
}
returnsdCard.readSD();
}
}

//TF卡接口
interfaceTFCard{
//读取TF卡功能
StringreadTF();

//写入TF卡功能
voidwriteTF(Stringmsg);
}

//TF卡实现类
classTFCardImplimplementsTFCard{
@Override
publicStringreadTF(){
Stringmsg="sdcardreadamsg:hellotfcard";
returnmsg;
}

@Override
publicvoidwriteTF(Stringmsg){
System.out.println("tfcardwritemsg:"+msg);
}
}

//定义适配器类(SD兼容TF)
classSDAdapterTFimplementsSDCard{
privateTFCardtfCard;

publicSDAdapterTF(TFCardtfCard){
this.tfCard=tfCard;
}

@Override
publicStringreadSD(){
System.out.println("adapterreadtfcard");
returntfCard.readTF();
}

@Override
publicvoidwriteSD(Stringmsg){
System.out.println("adapterwritetfcard");
tfCard.writeTF(msg);
}
}
原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容