写在前头:希望你了解到的不仅是模式,而学会用OOP的眼光分析问题,解决问题
关键字:连接
描述:适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。适配器不是在详细设计时添加的,而是解决正在服役的项目的问题。
原则:OFC,单一职责
区别:与代理模式的区别
示例:充电口转换
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| public interface USATool {
public void run();
}
public class USACharger implements USATool { @Override public void run() { System.out.println("insert to usa interface success!"); }
}
public interface ChinaTool {
public void run(String type); }
public class AdapterChager implements ChinaTool { private USATool usaChager; @Override public void run(String type) { if(type.equalsIgnoreCase("usatype")) { usaChager =new USACharger(); usaChager.run(); }else { System.out.println("At present, can't connect to this interface!"); } } }
public class ChinaCharger implements ChinaTool { private ChinaTool adapter;
@Override public void run(String type) { if(type.equalsIgnoreCase("chinatype")) { System.out.println("insert to china interface success!"); }else if(type.equalsIgnoreCase("usatype")) { adapter = new AdapterChager(); adapter.run(type); }else { System.out.println("At present, can't connect to this interface!"); } } public static void main(String[] args) { ChinaCharger charger= new ChinaCharger(); charger.run("chinatype"); charger.run("usatype"); charger.run("othertype"); } }
|