适用场景:旧系统的改造升级
实际场景:java.io.InputStreamReader(InputStream)等
1.一个被适配的类
package com.littlepage.AdapterPattern; /* * 被适配的类 */ public class Adaptee { public void request(){ System.out.println("对应可实现功能"); } }
2.客户端
package com.littlepage.AdapterPattern; /* * 客户端 */ public class Client { public void test1(Target t){ t.handleReq(); } public static void main(String[] args) { Client c=new Client(); Target t=new Adapter2(new Adaptee()); c.test1(t); } }
3.适配器写法1
package com.littlepage.AdapterPattern; /* * 适配器本身 */ public class Adapter extends Adaptee implements Target { @Override public void handleReq() { super.request(); } }
适配器写法2
package com.littlepage.AdapterPattern; public class Adapter2 implements Target{ private Adaptee adaptee; public Adapter2(Adaptee adaptee) { this.adaptee = adaptee; } @Override public void handleReq() { adaptee.request(); } }
UML图