适配器模式
适配器模式(Adapter),将一个类的接口转换为客户希望的另一个接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
系统的数据和行为都正确,但接口不符合时,我们应该考虑使用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
结构图
- Target:客户所期待的接口
public class Target {public void request() {System.out.println("普通请求");}
}
- Adaptee:需要适配的类
public class Adaptee {public void specificRequest() {System.out.println("特殊请求");}
}
Adapter:通过在内部包装一个Adaptee对象,把源接口转换成目标接口
public class Adapter extends Target {private Adaptee adaptee = new Adaptee();public void request() {adaptee.specificRequest();}
}
- 客户端
Target target = new Adapter();
target.request();
案例
有一场篮球比赛,一队的参赛人员,人员五湖四海,还有外籍的,那么就需要一个翻译(适配器)
人员分为:前锋,中锋,后卫,设置一个球员类,需要进攻和防守的方法即可。
public abstract class Player {protected String name;public Player(String name) {this.name = name;}abstract void attack(); // 进攻abstract void defense(); // 防守
}
- 前锋,中锋,后卫
// 前锋
public class Forwards extends Player {public Forwards(String name) {super(name);}@Overridevoid attack() {System.out.println("前锋 " + this.name + "进攻");}@Overridevoid defense() {System.out.println("前锋 " + this.name + "防守");}
}
// 中锋
public class Center extends Player {public Center(String name) {super(name);}@Overridevoid attack() {System.out.println("中锋 " + this.name + "进攻");}@Overridevoid defense() {System.out.println("中锋 " + this.name + "防守");}
}// 后卫
public class Guards extends Player {public Guards(String name) {super(name);}@Overridevoid attack() {System.out.println("后卫 " + this.name + "进攻");}@Overridevoid defense() {System.out.println("后卫 " + this.name + "防守");}
}
而现在有一个外籍中锋人员,我们还需要给他个翻译。
// 外籍中锋行为
public class ForeignCenter {private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}public void attackForeign() {System.out.println("外籍中锋" + this.name + "进攻");}public void defenseForeign() {System.out.println("外籍中锋" + this.name + "防守");}
}
- 适配器
public class Translator extends Player {private ForeignCenter foreignCenter = new ForeignCenter();public Translator(String name) {super(name);foreignCenter.setName(name);}@Overridevoid attack() {foreignCenter.attackForeign();}@Overridevoid defense() {foreignCenter.defenseForeign();}
}
- 客户端调用
Player forwards = new Forwards("张三");
forwards.attack();Player guards = new Guards("李四");
guards.defense();Player center = new Translator("Mike");
center.attack();
center.defense();