1.类适配器模式
package com.jmj.pattern.adapter.class_adapter;/*** 目标接口*/
public interface SDCard {//从SD卡中读取数据String readSD();//往SD卡中写数据void writeSD(String msg);}
package com.jmj.pattern.adapter.class_adapter;/*** 具体的SD卡类*/
public class SDCardImpl implements SDCard{@Overridepublic String readSD() {String msg="SDCard read msg : hello word SD";return msg;}@Overridepublic void writeSD(String msg) {System.out.println("SDCard write msg :" + msg);}
}
package com.jmj.pattern.adapter.class_adapter;/*** 适配者类的接口*/
public interface TFCard {//从TF卡中读取数据String readTF();//往TF卡中写数据void writeTF(String msg);}
package com.jmj.pattern.adapter.class_adapter;/*** 适配者类*/
public class TFCardImpl implements TFCard{@Overridepublic String readTF() {return "TFCard read msg: hello word TFCard";}@Overridepublic void writeTF(String msg) {System.out.println("TFCard write msg :"+msg);}}
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();}}
package com.jmj.pattern.adapter.class_adapter;/*** 适配器类*/
public class SDAdapterTF extends TFCardImpl implements SDCard {@Overridepublic String readSD() {System.out.println("adapter read tf card");return readTF();}@Overridepublic void writeSD(String msg) {System.out.println("adapter wirte tf card");writeTF(msg);}
}
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.对象适配器模式
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;}@Overridepublic String readSD() {System.out.println("adapter read tf card");return tfCard.readTF();}@Overridepublic void writeSD(String msg) {System.out.println("adapter wirte tf card");tfCard.writeTF(msg);}
}