1.类适配器模式
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 目标接口
*/
public interface SDCard {
//从SD卡中读取数据
String readSD();
//往SD卡中写数据
void writeSD(String msg);
}
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 具体的SD卡类
*/
public class SDCardImpl implements SDCard{
@Override
public String readSD() {
String msg="SDCard read msg : hello word SD";
return msg;
}
@Override
public void writeSD(String msg) {
System.out.println("SDCard write msg :" + msg);
}
}
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 适配者类的接口
*/
public interface TFCard {
//从TF卡中读取数据
String readTF();
//往TF卡中写数据
void writeTF(String msg);
}
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 适配者类
*/
public class TFCardImpl implements TFCard{
@Override
public String readTF() {
return "TFCard read msg: hello word TFCard";
}
@Override
public void writeTF(String msg) {
System.out.println("TFCard write msg :"+msg);
}
}
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 计算机类
*/
public class Computer {
//从SD卡中读取数据
public String readSD(SDCard sdCard) {
if (sdCard == null) {
throw new NullPointerException("sd card is not null");
}
return sdCard.readSD();
}
}
java
package com.jmj.pattern.adapter.class_adapter;
/**
* 适配器类
*/
public class SDAdapterTF extends TFCardImpl implements SDCard {
@Override
public String readSD() {
System.out.println("adapter read tf card");
return readTF();
}
@Override
public void writeSD(String msg) {
System.out.println("adapter wirte tf card");
writeTF(msg);
}
}
java
package com.jmj.pattern.adapter.class_adapter;
public class Client {
public static void main(String[] args) {
Computer computer = new Computer();
String s = computer.readSD(new SDCardImpl());
System.out.println(s);
System.out.println("=======================");
//使用该电脑 读取TF卡中的数据
//定义适配器类
Computer computer1 = new Computer();
String s1 = computer1.readSD(new SDAdapterTF());
System.out.println(s1);
}
}
2.对象适配器模式
java
package com.jmj.pattern.adapter.object_adapter;
import com.jmj.pattern.adapter.class_adapter.TFCardImpl;
/**
* 适配器类
*/
public class SDAdapterTF implements SDCard {
private TFCard tfCard;
public SDAdapterTF(TFCard tfCard){
this.tfCard=tfCard;
}
@Override
public String readSD() {
System.out.println("adapter read tf card");
return tfCard.readTF();
}
@Override
public void writeSD(String msg) {
System.out.println("adapter wirte tf card");
tfCard.writeTF(msg);
}
}